Search code examples
javaspringspring-security

How to switch to HTTP basic login for Spring Authorization Server?


Minimal configuration for OAuth 2 Spring Authz Server (spring-boot-starter-oauth2-authorization-server) works fine:

@Configuration
public class SecurityConfig {
    @Bean
    @Order(1)
    public SecurityFilterChain authServer(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults());
        http.exceptionHandling((e) -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")));
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain defaultChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
                .formLogin(Customizer.withDefaults())
                .build();
    }
}

This redirect's unauthenticated users to Spring's default login form. I, however, would like to use HTTP basic authentication which opens browser's native popup. This is what I tried:

@Configuration
public class SecurityConfig {
    @Bean
    @Order(1)
    public SecurityFilterChain authServer(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults());
        http.exceptionHandling((e) -> e.authenticationEntryPoint(new BasicAuthenticationEntryPoint()));
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain defaultChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults())
                .formLogin(f -> f.disable())
                .build();
    }
}

This does open basic login pop-up, but it keeps reappearing on login again and again. What am I doing wrong?


Solution

  • You can't use Basic auth to authenticate users against an OAuth2 authorization server.

    To authenticate users on an OAuth2 authorization server, you have to use authorization_code flow and this will involve an HTML form served by the authorization server.

    All you can do if you don't like the default, is style or replace Spring login form (use the http.formLogin() DSL as usual).