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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…