spring-security在AuthenticationManager中自定义注入AuthenticationPro



这可能是个新手问题。我想在Spring AuthenticationManager内部注入CustomAuthenticationProvider。我在网上发现了很多这样做的例子:

<authentication-manager>
    <authentication-provider ref="CustomAuthenticationProvider"/>
</authentication-manager>

如何使用Java Config类来实现这一点?

Spring提供了AuthenticationManager的一个默认实现,即ProviderManager。ProviderManager有一个构造函数,它接受一组身份验证提供程序

public ProviderManager(List<AuthenticationProvider> providers) {
    this(providers, null);
}

如果你想,你可以通过扩展ProviderManager 来使用它

public class MyAuthenticationManager extends ProviderManager implements AuthenticationManager{
public MyAuthenticationManager(List<AuthenticationProvider> providers) {
    super(providers);
    providers.forEach(e->System.out.println("Registered providers "+e.getClass().getName()));
   }
}

然后在Java安全配置中,您可以添加自定义身份验证管理器。

@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return new MyAuthenticationManager(Arrays.asList(new CustomAuthenticationProvider()));
}

最新更新