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

WebSecurityConfigurerAdapter已废弃,如何替换指定认证配置代码?

新版Spring Security 替代旧版认证配置方案

你的旧代码核心是完成三个配置:绑定自定义用户服务、指定密码编码器、关闭认证后凭证自动擦除。在Spring Security 6.x+版本中,官方已弃用WebSecurityConfigurerAdapter,改用基于Bean的配置方式,替代代码如下:

1. 注册核心组件Bean

首先将自定义的UserDetailsService和PasswordEncoder注册为Spring Bean:

// 注册自定义用户服务
@Bean
public UserDetailsService userDetailsService() {
    return yourCustomUserService; // 替换为你的UserDetailsService实例
}

// 注册密码编码器,示例为BCrypt,可替换为你使用的编码器
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

2. 配置认证提供者并关闭凭证擦除

创建DaoAuthenticationProvider Bean,设置核心属性并关闭凭证擦除:

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
    authProvider.setEraseCredentials(false); // 对应旧代码的eraseCredentials(false)
    return authProvider;
}

3. 配置SecurityFilterChain

在安全过滤器链中引入上述认证提供者,完成整体安全配置:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated() // 根据你的业务需求调整授权规则
        )
        .authenticationProvider(authenticationProvider())
        .formLogin(form -> form // 可替换为你需要的认证方式,如HTTP Basic、OAuth2等
            .loginPage("/login") // 示例自定义登录页,按需配置
            .permitAll()
        );

    return http.build();
}

关键说明

  • 旧代码中AuthenticationManagerBuilder的配置逻辑,现在通过DaoAuthenticationProvider这个具体的认证提供者来实现,更符合组件化设计。
  • setEraseCredentials(false)会保留认证后的凭证信息(如密码),如果你的业务不需要保留,可移除该配置(默认值为true)。

内容的提问来源于stack exchange,提问作者gold-three

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:57:43