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

新版Spring Security如何替代旧版configure认证配置方法?

新版Spring Security实现DaoAuthenticationProvider认证配置

1. 定义DaoAuthenticationProvider Bean

旧版中通过configure(AuthenticationManagerBuilder)配置的DaoAuthenticationProvider,在新版里直接定义为Spring Bean即可,把你的FakeApplicationUserDaoService(需实现UserDetailsService接口)和密码编码器绑定到Provider上:

@Bean
public DaoAuthenticationProvider daoAuthenticationProvider(FakeApplicationUserDaoService userDetailsService, PasswordEncoder passwordEncoder) {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    // 设置用户数据源
    authProvider.setUserDetailsService(userDetailsService);
    // 设置密码加密器,必须配置,否则认证会失败
    authProvider.setPasswordEncoder(passwordEncoder);
    // 可选:是否隐藏"用户不存在"的错误信息,默认true,设为false可以返回更明确的错误
    // authProvider.setHideUserNotFoundExceptions(false);
    return authProvider;
}

2. 配置SecurityFilterChain并注入Provider

在你已有的SecurityFilterChain配置中,将上面定义的DaoAuthenticationProvider注入并添加到HttpSecurity的认证链里:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, DaoAuthenticationProvider daoAuthenticationProvider) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            // 根据你的业务需求配置权限规则,这里示例为所有请求需认证
            .anyRequest().authenticated()
        )
        // 配置登录方式,这里用表单登录作为示例,可根据实际调整(如HTTP Basic、OAuth2等)
        .formLogin(form -> form.permitAll())
        // 加入自定义的认证Provider
        .authenticationProvider(daoAuthenticationProvider);
    
    return http.build();
}

3. 补充PasswordEncoder Bean

Spring Security要求必须配置密码编码器,所以需要定义对应的Bean(示例用BCrypt):

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

逻辑对应说明

旧版configure(AuthenticationManagerBuilder)里的核心逻辑(绑定UserDetailsService、PasswordEncoder到DaoAuthenticationProvider),现在通过Spring Bean的方式拆分实现:

  • DaoAuthenticationProvider作为独立Bean负责封装认证逻辑
  • SecurityFilterChain负责将Provider纳入整体安全过滤链中
  • Spring会自动处理Provider的注入和使用,不需要手动构建AuthenticationManager(除非有特殊需求)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:00:59