Java – How to allow “/api/**” through my basic authentication configuration and into my oauth configuration in Spring Security

How to allow “/api/**” through my basic authentication configuration and into my oauth configuration in Spring Security… here is a solution to the problem.

How to allow “/api/**” through my basic authentication configuration and into my oauth configuration in Spring Security

I have an app that uses both Basic Auth and OAuth2.

Some URLs use Basic Auth authorization, and “/api/**” uses OAuth2 authorization.

Currently, I have two Java configuration files (WebSecurityConfigurerAdapter and ResourceServerConfigurerAdapter).

Each configuration file defines a public void configure (HttpSecurity http) method.

The problem I’m having is that I need an elegant way to tell my app if it’s using basic authentication or OAuth2 for a given URL request.

Currently I’m using requestMatchers to achieve this:

@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 isn’t “/api/**”, I need to add it to the requestMatcher section of my WebSecurityConfig… This can lead to silly mistakes in the future.

Is there a way to do a requestMatcher search based on a negative leading regular expression? I tried this using a regular expression: ^(?!) /api) but since it doesn’t actually return MATCH but only “find == true”, it doesn’t seem to get the job done.

Any ideas/suggestions?

Solution

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.

Related Problems and Solutions