Using Httpsecurity. requestMatchers in Class Resourceserverconfiguration. Configure in Spring Oauth2
I Have Been Struggling to Understand How and When to Use Httpsecurity. requestMatchers. Though I Use Httpsecurity. requestMatchers but I Have Call...
I have been struggling to understand how and when to use HttpSecurity.requestMatchers. Though I use HttpSecurity.requestMatchers but I have call authorizeRequests and antMatchers to specify the security rules.
When should I use
http.requestMatchers()
.antMatchers("/secure/**","/patients/**","/patient/**", "/hello/**")
.and()
.authorizeRequests().antMatchers("/secure/**","/books/**","/book/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
over
http
.authorizeRequests().antMatchers("/secure/**","/books/**","/hello/**", "/hello/**")
.hasAnyRole("ADMIN","USER");
A scenario would help me to understand the use-case of HttpSecurity.requestMatchers
I did look into requestMatchers, but still not clear to me
1 Answer
If you need to configure multiple HttpSecurity in your application, than you would typically use HttpSecurity.requestMatchers() or one of the alternative (but similar) configuration options:
HttpSecurity.requestMatcher(RequestMatcher)HttpSecurity.antMatcher(String)HttpSecurity.mvcMatcher(String)HttpSecurity.regexMatcher(String)
See the reference in 6.10 Multiple HttpSecurity
For example, if your application has a set of API's rooted at the base path /api and another category of endpoints for the admin section of the application rooted at the base path /admin, than you might define 2x WebSecurityConfigurerAdapter for your application as such:
@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");
}
}
}
However, if you only provide 1x WebSecurityConfigurerAdapter than you don't need to configure HttpSecurity.requestMatchers() (or any of the alternatives) because it will automatically default to HttpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE). So for these configuration cases, this is sufficient:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(...
}
}
Hopefully, this makes sense?