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

Spring Security已弃用AuthenticationManager的Lambda式配置改写求助

解决方案

方式一:单独定义AuthenticationManager Bean(推荐)

直接注入AuthenticationManagerBuilder完成配置,避免依赖HttpSecurity内部对象,代码更简洁规范:

@Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(customUserDetailService)
        .passwordEncoder(passwordEncoder());
    return auth.build();
}

方式二:整合到SecurityFilterChain的Lambda配置中

贴合Spring Security的Lambda DSL风格,将AuthenticationManager配置逻辑直接嵌入SecurityFilterChain的整体配置:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // 先配置授权规则等其他安全逻辑
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        // Lambda方式配置AuthenticationManager
        .authenticationManager(builder -> {
            builder.userDetailsService(customUserDetailService)
                .passwordEncoder(passwordEncoder());
        });
    return http.build();
}

说明

原代码通过http.getSharedObject(AuthenticationManagerBuilder.class)获取构建器属于内部用法,新版本Spring Security不推荐。以上两种方式均移除了该依赖,同时完整保留了原有的认证逻辑(自定义UserDetailsService+密码编码器),其中第二种完全采用Lambda式配置,符合当前Spring Security最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:16:24