我一直在努力了解如何以及何时使用HttpSecurity.requestMatchers
。尽管我使用HttpSecurity.requestMatchers
,但是我已经调用authorizeRequests
和antMatchers
来指定安全规则。
我什么时候应该使用
http.requestMatchers()
.antMatchers("/secure/**","/patients/**","/patient/**", "/hello/**")
.and()
.authorizeRequests().antMatchers("/secure/**","/books/**","/book/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
在
http
.authorizeRequests().antMatchers("/secure/**","/books/**","/hello/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
一个场景将帮助我理解HttpSecurity.requestMatchers
的用例
我确实调查了requestMatchers,但仍然不清楚
答案 0 :(得分:2)
如果您需要在应用程序中配置多个HttpSecurity
,则通常会使用HttpSecurity.requestMatchers()
或其他(但类似)配置选项之一:
HttpSecurity.requestMatcher(RequestMatcher)
HttpSecurity.antMatcher(String)
HttpSecurity.mvcMatcher(String)
HttpSecurity.regexMatcher(String)
例如,如果您的应用程序的一组API的根目录是基本路径/api
,而应用程序的admin部分的另一类终结点的根目录是基本路径/admin
,那么您可能会像这样为您的应用程序定义2x WebSecurityConfigurerAdapter
:
@EnableWebSecurity
public class SecurityConfig {
@Configuration
@Order(1)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/endpoint1")
.hasRole("USER1");
}
}
@Configuration
public static class AdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/admin/**")
.and()
.authorizeRequests()
.antMatchers("/admin/endpoint1")
.hasRole("ADMIN1");
}
}
}
但是,如果您仅提供1x WebSecurityConfigurerAdapter
,则不需要配置HttpSecurity.requestMatchers()
(或任何替代方法),因为它将自动默认为HttpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE)
。因此,对于这些配置情况,这就足够了:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(...
}
}
希望这有意义吗?