您需要antMatcher
多个HttpSecurity
,请参阅Spring Security Reference:
5.7 多重HttpSecurity
我们可以配置多个 HttpSecurity 实例,就像我们可以有多个<http>
块一样。关键是要延长WebSecurityConfigurationAdapter
多次。例如,以下是对以 . 开头的 URL 进行不同配置的示例/api/
。
@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
应首先考虑的实例。
3http.antMatcher
声明这HttpSecurity
仅适用于以/api/
4 创建另一个实例WebSecurityConfigurerAdapter
。如果 URL 不以此配置开头,/api/
则将使用此配置。这个配置被认为是 afterApiWebSecurityConfigurationAdapter
因为它有一个@Order
值 after 1
(没有@Order
默认为 last)。
在您的情况下,您不需要antMatcher
,因为您只有一种配置。您修改后的代码:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()