Can we define both Bearer token authentication and Basic authentication in a single module of Spring Boot?

Viewed 277

I have a requirement where I have a controller which just needs Basic Authentication, while other controllers need to authenticate via Bearer token. Is it possible in a single module of the Spring Boot application to implement both securities? If yes how should I define it in WebSecurityConfigurerAdapter, filters, and so on?

1 Answers

Yes, this is possible.

You would basically implement two different WebSecurityConfigurerAdapters, each configuring their own HttpSecurity object and each being applied to distinct sets of requests of your application. Have a look at the following security configuration example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private static final RequestMatcher BASIC_REQUESTS = new AntPathRequestMatcher("/api/basic/**");

    private static final RequestMatcher BEARER_REQUESTS = new NegatedRequestMatcher(BASIC_REQUESTS);

    @Configuration
    @Order(1)
    public static class BasicAuthSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(BASIC_REQUESTS).authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .httpBasic()
                    ...
        }
    }

    @Configuration
    @Order(2)
    public static class BearerAuthSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(BEARER_REQUESTS).authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .addFilter(...)
                    ...
        }
    }

}

This tells Spring to handle all requests matching the path /api/basic/** with a basic authentication scheme and all other requests with, e.g., a custom filter chain performing some bearer authentication. HttpSecurity.requestMatcher(...) makes Spring apply the configuration only for requests that match the given request matcher.

Note that you have to manually set an order for your WebSecurityConfigurerAdapters because otherwise Spring would try to initialize both beans with the default priority, which would result in a conflict.

Related