返回 导航

SpringBoot / Cloud

hangge.com

SpringBoot - 安全管理框架Spring Security使用详解8(配置多个HttpSecurity)

作者:hangge | 2020-01-05 08:10
    在之前的文章中我们都只配置一个 HttpSecurity,如果业务比较复杂,我们也可以配置多个 HttpSecurity,实现对 WebSecurityConfigurerAdapter 的多次扩展。

八、配置多个 HttpSecurity

1,样例代码

(1)配置多个 HttpSecurity 时,MultiHttpSecurityConfig 不需要继承 WebSecurityConfigurerAdapter,而是在 MultiHttpSecurityConfig 中创建静态内部类继承 WebSecurityConfigurerAdapter 即可。
注意:静态内部类上添加 @Configuration 注解和 @Order 注解,@Order 注解表示该配置的优先级,数字越小优先级越大,未加 @Order 注解的配置优先级最小。
(2)这里我们创建了两个静态内部类来配置两个不同的 HttpSecurity,一个用来处理“/admin/**”模式的 URL,另一个处理其它的 URL
@Configuration
public class MultiHttpSecurityConfig{
    // 指定密码的加密方式
    @SuppressWarnings("deprecation")
    @Bean
    PasswordEncoder passwordEncoder(){
        // 不对密码进行加密
        return NoOpPasswordEncoder.getInstance();
    }

    // 配置用户及其对应的角色
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password("123").roles("DBA")
                .and()
                .withUser("admin").password("123").roles("ADMIN")
                .and()
                .withUser("hangge").password("123").roles("USER");
    }

    // 下面配置专门用来处理 "/admin/**" 模式的URL
    @Configuration
    @Order(1)
    public static class AdminSecurityConfig
            extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/admin/**").authorizeRequests()
                    .anyRequest().hasRole("ADMIN");
        }
    }

    // 下面配置用来处理其它的URL
    @Configuration
    public static class OtherSecurityConfig
            extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests() // 开启 HttpSecurity 配置
                .anyRequest().authenticated() // 用户访问其它URL都必须认证后访问(登录后访问)
                .and().formLogin().loginProcessingUrl("/login").permitAll()//开启表单登录并配置登录接口
                .and().csrf().disable(); // 关闭csrf
        }
    }
}

2,运行测试

(1)启动项目,我们使用 root 用户进行登录,所以登录后可以访问除 /admin/* 外所有接口。

(2)而由于 /admin/hello 接口需要 ADMIN 角色,因此 root 用户仍然无法访问。
评论

全部评论(0)

回到顶部