Spring Security配置多个HttpSecurity

我们可以通过继承WebSecurityConfigurationAdapter 去配置多个HttpSecurity实例,例如,下面是一个以/api/开头的url的不同配置的示例:

@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) { 1
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }
    @Configuration
    @Order(1)                                                        2
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")                               3
                .authorizeRequests()
                    .anyRequest().hasRole("ADMIN")
                    .and()
                .httpBasic();
        }
    }
    @Configuration                                                   4
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
    }
}
  1. 正常配置一个基于内存的用户和权限信息
  2. 创建一个WebSecurityConfigurerAdapter的实例并在类上面加上@Order注解,用于明确提出应该首先使用哪个WebSecurityConfigurerAdapter实例。
  3. 这个http.antMatcher确定了这个HttpSecurity将使用以/api/开头的URL。
  4. 再配置其他WebSecurityConfigurerAdapter的实例,如果这个URL不是以/api/开头将被使用。这个配置在ApiWebSecurityConfigurationAdapter之后被调用,因为在@Order注解的value = 1(没有添加@Order注解默认在最后调用)。

猜你喜欢

转载自blog.csdn.net/qq_22771739/article/details/84308847