美文网首页技术干货
第2章4-Spring Security权限框架学习与演练-基于

第2章4-Spring Security权限框架学习与演练-基于

作者: yust5273 | 来源:发表于2019-02-03 19:26 被阅读3次
    • 快速搭建Spring Boot + Spring Security环境
    • 常用Case实现

    快速搭建Spring Boot + Spring Security环境

    简介

    Spring Boot是基于Spring的一套全新的框架,设计目的是为了简化Spring应用的初始搭建,以及开发过程。该框架使用了特定的方式来进行配置。从而使得开发人员不在需要样板化的配置。通过这种方式Spring Boot致力于在蓬勃发展的快速应用开发领域成为领导者。
    Spring Boot 有很多特点:1.可以创建独立的Spring应用程序。2.可以嵌入tomcat,无需部署war文件3.简化maven的配置,自动配置Spring4. 提供生产就绪型功能,如指标,健康检查和外部配置等。5. 没有xml配置。

    实操
    1. 访问 https://start.spring.io/
      生成Spring Security环境初始化项目
    2. 配置IDEA
      项目导入IDEA,检查maven setting.xml文件配置是否正确。
      项目结构如下:


      项目结构
    3. 启动项目
    • 访问主页面被拦截自动跳到登录页面


      访问主页面被拦截自动跳到登录页面
    1. 新建SpringSecurityConfig类,配置一些Spring Security的配置。
    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    
        /**
         * HTTP请求的拦截
         * 1.设置主路径可以访问
         * 2.其他请求经过验证
         * 3.注销可以访问
         * 4.允许表单登录
         *
         * 5.关闭csrf认证
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .logout().permitAll()
                    .and()
                    .formLogin();
            http.csrf().disable();
        }
    
        /**
         * 设置不拦截 JS CSS Images
         * @param web
         * @throws Exception
         */
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/js/**","/css/**","/images/**");
        }
    }
    
    1. DemoApplication页面配置
    @SpringBootApplication
    @RestController
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
        @RequestMapping("/")
        public String home(){
            return "hello spring boot";
        }
        @RequestMapping("hello")
        public String hello(){
            return "hello world";
        }
    }
    
    1. 访问验证
    • 访问主页面没有被拦截


      访问主页面没有被拦截
    • 访问hello被拦截自动跳到登录页面


      访问hello被拦截自动跳到登录页面

    ============================
    环境已经OK了,接下来会基于当前的环境开发几个case。

    相关文章

      网友评论

        本文标题:第2章4-Spring Security权限框架学习与演练-基于

        本文链接:https://www.haomeiwen.com/subject/djtusqtx.html