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

一、实现配置多个 HttpSecurity

前期的配置和学习基本和本系列的文章都一样,
本篇文章不再赘述:学习 Spring Security 看这一篇博客就够了

@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 方法的访问则不可以

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/nanhuaibeian/article/details/108816655