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

Spring Boot中替换已弃用的WebSecurityConfigurerAdapter方案求助

替换WebSecurityConfigurerAdapter的Spring Security配置方案

以下是适配Spring Security 5.7+(弃用WebSecurityConfigurerAdapter后的版本)的配置代码,完全替代你原有的实现:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .logout()
                .permitAll();

        return http.build();
    }
}

关键改动说明

  1. 移除继承关系:不再继承WebSecurityConfigurerAdapter,改用基于Bean的配置模式(官方推荐的弃用后替代方案)。
  2. HTTP安全配置迁移:用SecurityFilterChain Bean替代原configure(HttpSecurity)方法,注意使用authorizeHttpRequests()替代已弃用的authorizeRequests()。
  3. 认证管理器配置:通过AuthenticationConfiguration获取AuthenticationManager,原DaoAuthenticationProvider作为Bean会自动被注册到认证管理器中,无需手动调用配置方法。
  4. 原有核心Bean保留:UserDetailsService、BCryptPasswordEncoder、DaoAuthenticationProvider的定义逻辑完全保留,功能与之前一致。

可选扩展

如果需要手动构建AuthenticationManager(而非依赖AuthenticationConfiguration),可以替换成以下实现:

@Bean
public AuthenticationManager authenticationManager() {
    DaoAuthenticationProvider authProvider = authenticationProvider();
    return new ProviderManager(authProvider);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:58:20