Search code examples
javaspringspring-bootspring-security

Custom provider getting execude on every request with Spring 6 Basic Authentication


Currently working on upgrading my web application from Spring Boot 2 to Version 3. As Spring Boot 3 uses Spring 6 I needed to update my security configuration. After my changes I noticed that my custom authentication provider is getting called on every request which leads to heavy database traffic. It's not happening if I use the spring default login form but with basic authentication.

Here is my sample security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(new CustomAuthenticationProvider());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize
                        .anyRequest().authenticated()
                )
                .httpBasic();
        return http.build();
    }
}

My Provider looks like:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        if ("admin".equals(username) && "admin".equals(password)) {
            var user = User.withUsername("admin").password("admin").authorities(new ArrayList<>()).build();
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
        } else {
            throw new
                    BadCredentialsException("system authentication failed");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

Behavior in short:

SecurityConfig Behavior
.formLogin() 1x Login / Provider-Call
.httpBasic() 1x Login per Session / 1x Provider-Call per request

What can I do to get the old behavior back as it was with Spring 5 / Spring Boot 2?


Solution

  • for everyone having the same issue, you can restore the old session behavior by setting the session creation policy in your security filter chain:

    .httpBasic(withDefaults())
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    ...