You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot3升级后Basic认证下自定义Provider每次请求执行的解决办法

问题原因

Spring Boot 3(基于Spring 6)中,HttpBasicAuthenticationFilter默认不会将认证成功的Authentication对象存入Http Session,导致每次请求都需要重新调用自定义AuthenticationProvider进行认证;而表单登录(formLogin())默认依赖会话存储认证状态,因此仅调用一次Provider。

解决方案

要恢复Spring Boot 2的行为,需配置Spring Security将Basic认证结果存入Http Session,后续请求直接从会话读取认证信息,无需重复调用Provider。具体修改如下:

1. 配置SecurityContextRepository

在SecurityFilterChain中添加会话存储配置,指定使用HttpSessionSecurityContextRepository持久化认证状态:

@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()
            )
            // 配置认证状态存储到HttpSession
            .securityContext(securityContext -> securityContext
                .securityContextRepository(new HttpSessionSecurityContextRepository())
            )
            .httpBasic(httpBasic -> httpBasic
                // 确保认证成功后将上下文存入会话
                .successHandler((request, response, authentication) -> {
                    SecurityContext context = SecurityContextHolder.createEmptyContext();
                    context.setAuthentication(authentication);
                    request.getSession().setAttribute(
                        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
                        context
                    );
                })
            )
            // 会话创建策略保持默认的按需创建
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            );
        return http.build();
    }
}

2. 确保Authentication对象可序列化

自定义AuthenticationProvider返回的UsernamePasswordAuthenticationToken需支持序列化(Spring Security默认实现已满足)。若你后续自定义了User实体类,需确保其实现Serializable接口。当前示例中使用的org.springframework.security.core.userdetails.User已符合要求,无需修改。

3. 效果验证

修改后,首次Basic认证请求会调用CustomAuthenticationProvider,认证成功后信息存入Http Session;同一会话内的后续请求将直接从会话读取认证状态,不再触发Provider调用,数据库流量将恢复至Spring Boot 2时期的水平。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:55:36