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

一、实现配置多个 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🚀

posted @ 2020-10-06 16:56  AI乔治  阅读(2110)  评论(0编辑  收藏  举报

作者微信号:wm1106701116 (备注:博客园) 加入微信架构群,获取架构师学习资料。