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

Spring Boot2+Spring Security5非XML配置下设置ProviderManager的eraseCredentialsAfterAuthentication为false

如何在Spring Boot 2 + Spring Security 5中关闭认证后的凭证清除

嘿,这个需求我刚好在项目里踩过坑,不用XML配置,纯Java代码就能轻松搞定。Spring Security的ProviderManager默认会在认证成功后清除凭证(比如用户密码这类敏感信息),要把eraseCredentialsAfterAuthentication设为false,分两种配置场景给你讲清楚:

1. 基于已废弃的WebSecurityConfigurerAdapter配置(适合旧项目)

如果你的项目还在使用WebSecurityConfigurerAdapter(Spring Boot 2.7版本以前常用),可以直接在configure(AuthenticationManagerBuilder)方法里获取并修改ProviderManager的属性:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 先配置自定义用户详情服务和密码编码器
        auth.userDetailsService(customUserDetailsService)
            .passwordEncoder(passwordEncoder());
        
        // 获取构建好的ProviderManager,修改凭证清除属性
        ProviderManager providerManager = (ProviderManager) auth.getOrBuild();
        providerManager.setEraseCredentialsAfterAuthentication(false);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

2. 基于SecurityFilterChain的最新配置(官方推荐)

从Spring Boot 2.7开始,WebSecurityConfigurerAdapter已经被废弃,官方推荐用SecurityFilterChain来配置安全规则。这种情况下,我们可以通过自定义AuthenticationManager Bean来修改属性:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.permitAll()); // 根据你的业务需求调整登录规则

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        AuthenticationManager authManager = authConfig.getAuthenticationManager();
        // 强转为ProviderManager并修改凭证清除属性
        if (authManager instanceof ProviderManager) {
            ((ProviderManager) authManager).setEraseCredentialsAfterAuthentication(false);
        }
        return authManager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

额外注意事项

  • ProviderManager的这个属性是全局开关,设为false后,所有认证成功后的用户凭证都会被保留,包括密码这类敏感信息,一定要确认你的业务场景确实需要保留这些数据,避免带来安全风险。
  • 如果你用了自定义的AuthenticationProvider,也可以单独给它设置setEraseCredentials(false),但全局修改ProviderManager的方式更高效统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:54:02