Spring Boot/Spring Security Choose Between Multiple Authentication Providers Based On Path

Viewed 1393

I have configured my application as such:

I have two authentication providers (provider1 and provider2) and I want to use them for different endpoints:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/api/v1").authenticated();
    http.authorizeRequests().antMatchers("/api/v2").authenticated();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(provider1);
    auth.authenticationProvider(provider2);
}

Right now what happens is if I call /api/v2 provider1 gets called and if does not raise an exception or return false then only does provider2 get called.

// In org.springframework.security.authentication.ProviderManager

for (AuthenticationProvider provider : getProviders()) {
        try {
            result = provider.authenticate(authentication);

            if (result != null) {
                copyDetails(authentication, result);
                break;
            }
        }
        ...
        ...
}

How can I make so that only provider2 gets called when I hit /api/v2?

Something like this:

http.authorizeRequests().antMatchers("/api/v2")
    .authenticated().authenticationProvider(provider2);

(I know there is a authenticationProvider on HttpSecurity, however, that is the exact same as calling AuthenticationManagerBuilder#authenticationProvider)

1 Answers
Related