Default to using SecurityContextHolderFilter instead of SecurityContextPersistenceFilter. This means that explicit saving of the SecurityContext is necessary rather than automatic saving of the SecurityContextHolder to the SecurityContextRepository.

Comment From: craigmit

I was upgrading from spring security 5 to 6 with a custom UsernamePasswordAuthenticationFilter, and the authentication was happening, but nothing was being allowed through. I think it was due to this change, as when I added:

http.securityContext((securityContext) -> securityContext.requireExplicitSave(false))

to my filter chain, everything started working again.

Comment From: skylarsutton

I was upgrading from spring security 5 to 6 with a custom UsernamePasswordAuthenticationFilter, and the authentication was happening, but nothing was being allowed through. I think it was due to this change, as when I added:

http.securityContext((securityContext) -> securityContext.requireExplicitSave(false))

to my filter chain, everything started working again.

The migration documentation is not clear on this, but if your CustomAuthenticationFilter extends spring's AbstractPreAuthenticatedProcessingFilter, you will want to inject the SecurityContextRepository.

e.g.

public class FooAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {

    public FooAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource, SecurityContextRepository securityContextRepository) {
        super();
        super.setAuthenticationManager(authenticationManager);
        super.setAuthenticationDetailsSource(authenticationDetailsSource);
        super.setSecurityContextRepository(securityContextRepository);
    }

    ...

}

Comment From: rakeshskc

I was facing the same issue when I was trying to upgrade spring framework 5 to 6, But after adding code below, everything started working fine,

http.securityContext((securityContext) -> securityContext.requireExplicitSave(false));