首页 > 解决方案 > 如何在 Spring Boot 中为 preAuthenticationChecks 和 postAuthenticationChecks 配置 UserDetailsChecker

问题描述

我正在寻找UserDetailsChecker在 Spring Boot 中为 preAuthenticationChecks 和/或 postAuthenticationChecks 配置“最佳实践”的解决方案(请参阅AbstractUserDetailsAuthenticationProviderDaoAuthenticationProvider)。

是否绝对有必要创建自定义DaoAuthenticationProvider

无法通过WebSecurityConfigurerAdapteror自定义它AuthenticationManagerBuilder

标签: springspring-bootspring-security

解决方案


回答我自己的问题:我搜索了 spring boot 源(v1.5.13.RELEASE 和 v2.0.2.RELEASE)grep- 没有结果。

至少在这个版本中,DaoAuthenticationProvider如果您想使用额外的认证前或认证后检查,您必须创建一个自定义。

编辑:“你必须创建一个自定义DaoAuthenticationProvider”这句话有点误导。在最近的一个项目中,我通过以下方式完成了它:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    @Autowired
    public void configureGlobal(
            AuthenticationManagerBuilder auth,
            MyUserAccountService myUserAccountService,
            PasswordEncoder passwordEncoder,
            MessageSourceAccessor messageSourceAccessor
    ) throws Exception {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        daoAuthenticationProvider.setUserDetailsService(myUserAccountService);
        daoAuthenticationProvider.setPostAuthenticationChecks(new UserAccountChecker(messageSourceAccessor));
        auth.authenticationProvider(daoAuthenticationProvider);
        auth.userDetailsService(myUserAccountService).passwordEncoder(passwordEncoder);
    }

[...]

}

UserAccountChecker implements UserDetailsChecker是一个发生(后)身份验证测试的类(另请参见 中的类DefaultPostAuthenticationChecksAbstractUserDetailsAuthenticationProvider


推荐阅读