After Spring Boot 3 update: Authentication token not saved in SecurityContext

In my application I have implemented custom otp authentication. It was working correctly with Spring Security 5 but after updating to boot3 and Spring Security 6 it stopped working. Authentication is working just fine but it seems that the authenticated object is not stored in context and subsequent requests responds with 401.

The security configuration looks like this:


    @Bean("otpSecurityFilterConfiguration")
        @Order(1)
        public SecurityFilterChain otpSecurityFilterChainConfiguration(HttpSecurity http) throws Exception {
    
            OtpAuthenticationFilter otpAuthenticationFilter = new OtpAuthenticationFilter(createOtpAuthenticationManager(),
                    authenticationSuccessHandler, authenticationFailureHandler);
    
            http
                    .securityMatcher(new AntPathRequestMatcher("/**"))
                    .addFilterBefore(otpAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                    .formLogin(form -> form.loginProcessingUrl("/login"))
                    .cors(Customizer.withDefaults())
                    .csrf(csrf -> csrf.disable())
                    .exceptionHandling(handler -> handler.authenticationEntryPoint(otpAuthenticationEntryPoint))
                    .authorizeHttpRequests(requests -> requests
                            .requestMatchers("/auth/sendOtp").permitAll()
                            .anyRequest().authenticated())
                    .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
                    .headers(headers -> headers
                            .contentTypeOptions(Customizer.withDefaults()));
    
            return http.build();
        }
    
    private AuthenticationManager createOtpAuthenticationManager() {
            return new ProviderManager(otpAuthProvider);
        }

And the otpAuthenticationFilter which extends AbstractAuthenticationProcessingFilter captures the /login request, creates authenticated token and process further


    @Slf4j
    public class OtpAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
            
            if (postOnly && !request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            }
            
            String code = request.getParameter("code");
            String uid = request.getParameter("uid");
            String email = request.getParameter("email");
            
            log.info("Received authentication request with email: {} and uid: {}", email, uid);
            
            String sessionKey = OtpAuthUtils.getSessionKey(uid, email);
            
            OtpCode sessionCode = (OtpCode) request.getSession().getAttribute(sessionKey);
            validateOtpCode(sessionCode, code, sessionKey, request);
            log.info("Otp code validated successfully. User {} is now authenticated", email);
            
            OtpAuthenticationToken authRequest = new OtpAuthenticationToken(email, uid);
    
            setDetails(request, authRequest);
    
            return this.getAuthenticationManager().authenticate(authRequest);
        }

Above code works just fine, token is authenticated, OtpProvider, which creates UserDetails from token is also called.

Now according to https://docs.spring.io/spring-security/reference/5.8/migration/servlet/session-management.html#_require_explicit_saving_of_securitycontextrepository in Spring Security 6 context must be saved in securityContextRepository. This is the change from Spring Security 5 that may explain my case but my otp filter which extends AbstractAuthenticationProcessingFilter should have this handled. Method AbstractAuthenticationProcessingFilter#successfulAuthentication which creates authenticated SecurityContext and saves the context in securityContextRepository is called.


protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
    context.setAuthentication(authResult);
    this.securityContextHolderStrategy.setContext(context);
    this.securityContextRepository.saveContext(context, request, response);

Finally i managed to make this work disabling securityContext explicit save. But it seems this is not a valid solution.

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

How to make this work without disabling explicit save?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật