adding okta oauth2 filter chain with another filter chain

Viewed 166

I have an application which is using a custom token based authentication. We are currently migrating the security to Okta Oauth2. In the process of migration, I need to keep both the security for sometime. That is, the clients of my APIs should have the flexibility to use either one of the security for sometime. My WebSecurityConfigurerAdapter is like this now

@Override
protected void configure(final HttpSecurity http)  throws Exception {
    http.authorizeRequests().antMatchers("/").permitAll().and()
    .csrf().disable()
    .cors().disable()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterAfter(tokenAuthFilter, X509AuthenticationFilter.class);
}

For the same antMatcher how can I add the okta Oauth2 security also so that either one of it should authenticate my API.

I am able write another WebSecurityConfigurerAdapter with .oauth2ResourceServer().jwt(); dedicatedly for OAuth2, but as the current existing custom token based security is also using the same antmatcher, one of it is only becoming active.

1 Answers

you can configure the AuthenticationManagerBuilder and let your Security invoke the authentication manager. This way you can chain your auth providers and if any of them can authenticate the request it will go through.

There is a good article from Baeldung about this: Multiple Authentication Providers in Spring Security

@EnableWebSecurity
public class MultipleAuthProvidersSecurityConfig extends WebSecurityConfigurerAdapter

@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthProvider())
            .authenticationProvider(new OctaOauth2Provider());
    }

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .cors().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            .and()
            .authorizeRequests()
            .antMatchers("/**") // matches any request
            .authenticated(); //invokes authentication providers
    }
}
Related