如何在不使用 WebSecurityConfigurerAdapter 的情况下添加额外的 AuthenticationProvider

sch*_*uch 6 spring-security

在 Spring Security 5.7 之前,可以通过以下方式AuthenticationProviders向全局添加附加内容AuthenticationManager

public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    ...

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

}
Run Code Online (Sandbox Code Playgroud)

Spring Security 5.7 已WebSecurityConfigurerAdapter弃用。

问题:我应该迁移此代码来解决弃用问题吗?

当我尝试将附加注册AuthenticationProvider为 时@Bean,基于用户名/密码的身份验证的自动创建的身份验证提供程序被替换,导致

No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken
Run Code Online (Sandbox Code Playgroud)

我阅读了博客文章https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter但没有发现有关向全局AuthenticationManager.

Ele*_*ana 6

如果你有一个,AuthenticationProvider你可以将它注册为一个 bean,Spring Security 将拾取它:

@Bean
public CustomAuthenticationProvider customAuthenticationProvider() {
    return new CustomAuthenticationProvider();
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以AuthenticationProviderHttpSecurity配置中添加额外的:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // ...
        .authenticationProvider(new CustomAuthenticationProvider());
    return http.build();
}
Run Code Online (Sandbox Code Playgroud)