当前位置 博文首页 > 文章内容

    一篇文章带你搞定 SpringSecurity 配置多个HttpSecurity 和实现对于方法安全的控制

    作者: 栏目:未分类 时间:2020-10-06 17:00:10

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    一、实现配置多个 HttpSecurity

    前期的配置和学习基本和本系列的文章都一样,

    @Configuration
    public class MultiHttpSecurityConfig {
    
        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Autowired
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("nlcs").password("$2a$10$G3kVAJHvmRrr6sOj.j4xpO2Dsxl5EG8rHycPHFWyi9UMIhtdSH15u").roles("admin")
                    .and()
                    .withUser("yolo").password("$2a$10$kWjG2GxWhm/2tN2ZBpi7bexXjUneIKFxIAaMYJzY7WcziZLCD4PZS").roles("user");
        }
    
        @Configuration
        @Order(1)
        public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
            }
        }
    
        @Configuration
        public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().anyRequest().authenticated()
                        .and()
                        .formLogin()
                        .loginProcessingUrl("/doLogin")
                        .permitAll()
                        .and()
                        .csrf().disable();
            }
        }
    }
    

      

    (1)当配置多个 httpsecurity 时,就不用像前面那样主方法继承 WebSecurityConfigurerAdapter,只需要内部的静态类继承 WebSecurityConfigurerAdapter 即可

    (2)当多个 httpsecurity 时,需要通过 @Order(1) 指定优先级

    二、实现方法安全的控制

    1. 编写配置类

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
    public class MultiHttpSecurityConfig {
    
        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Autowired
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("yolo").password("$2a$10$G3kVAJHvmRrr6sOj.j4xpO2Dsxl5EG8rHycPHFWyi9UMIhtdSH15u").roles("admin")
                    .and()
                    .withUser("nlcs").password("$2a$10$kWjG2GxWhm/2tN2ZBpi7bexXjUneIKFxIAaMYJzY7WcziZLCD4PZS").roles("user");
        }
    
        @Configuration
        @Order(1)
        public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
            }
        }
    
        @Configuration
        public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().anyRequest().authenticated()
                        .and()
                        .formLogin()
                        .loginProcessingUrl("/doLogin")
                        .permitAll()
                        .and()
                        .csrf().disable();
            }
        }
    }
    

      

    prePostEnabled 表示在方法前进行校验

    2. 编写 service

    @Service
    public class MethodService {
        @PreAuthorize("hasRole('admin')")
        public String admin(){
            return "hello admin";
        }
        //有 user 这个角色才可以访问
        @Secured("ROLE_user")
        public String user(){
            return "hello user";
        }
        @PreAuthorize("hasAnyRole('admin','user')")
        public String hello(){
            return "hello hello";
        }
    }
    

      

    @PreAuthorize("hasRole('admin')") 表示方法访问前对其进行验证,是否是 admin 权限

    3. 编写 controller

    @RestController
    public class HelloController {
    
        @Autowired
        MethodService methodService;
        @GetMapping("/admin")
        public String admin() {
            return methodService.admin();
        }
        @GetMapping("/user")
        public String user() {
            return methodService.user();
        }
        @GetMapping("/hello")
        public String hello() {
            return methodService.hello();
        }
    }
    

      

    对于 这三个接口都可以访问,但是对于接口里的具体方法,只有具有对应权限的用户才可以访问。

    4. 测试

    yolo 登录:它具有 admin 权限,可以访问 admin 接口及其方法,但是对于 user 方法的访问则不可以

    在这里插入图片描述

     

    看完三件事❤️

    如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:

    1. 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。

    2. 关注公众号 『 java烂猪皮 』,不定期分享原创知识。

    3. 同时可以期待后续文章ing?