Reputation: 1137
I have an app that uses both Basic Auth and OAuth2.
Some URLs are authorized using Basic Auth and "/api/**" is authorized using OAuth2.
Currently, I have two Java config files (WebSecurityConfigurerAdapter
and ResourceServerConfigurerAdapter
)
Each of the config files define a public void configure(HttpSecurity http)
method.
The trouble I'm having is that I need an elegant way to tell my app whether to use basic auth or oauth2 given the url request.
Currently I'm using requestMatchers
to make this happen:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.requestMatchers()
.antMatchers("/*", "/login/**", "/reviews/**")
.and()
.authorizeRequests()
.antMatchers("/*").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/img/**").permitAll()
.formLogin()
.loginPage("/login")
.successHandler(loginSuccessPostHandler)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/").permitAll()
.and()
.apply(getSpringSocialConfigurer());
}
}
@Configuration
public class OAuth2ServerConfig
{
@Configuration
@EnableResourceServer
protected static class Oauth2ServerConfig extends ResourceServerConfigurerAdapter
{
@Override
public void configure(HttpSecurity http) throws Exception
{
http.httpBasic().disable();
http.csrf().disable();
http.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/v1/**").access("#oauth2.hasScope('read')");
}
}
}
The problem is that every time I add a new URL that's NOT "/api/**", I'll need to add it into my WebSecurityConfig
's requestMatcher section... this could lead to silly bugs in the future.
Is there a way to have a requestMatcher search based on a negative lookahead regex? I tried this using the regex: ^(?!/api)
but since it doesn't actually return a MATCH and only returns a "find == true", it doesn't seem to get the job done.
Any thoughts / suggestions?
Upvotes: 3
Views: 2386
Reputation: 48893
You should use Order(...)
annotation on @Configuration
classes. Make your OAuth2ServerConfig
config first and serving only http.requestMatchers().antMatchers("/api/**")
and make your WebSecurityConfig
second (@Order(2)
) without http.requestMatchers()
to serve all rest URLs!
See details on https://stackoverflow.com/a/44871933/173149
Upvotes: 0
Reputation: 17009
You can use NegatedRequestMatcher:
A RequestMatcher that will negate the RequestMatcher passed in. For example, if the RequestMatcher passed in returns true, NegatedRequestMatcher will return false. If the RequestMatcher passed in returns false, NegatedRequestMatcher will return true.
Upvotes: 2