java - 使用 Spring Security 进行身份验证
问题描述
在 Spring Security 中使用身份验证时,我有些困惑。有两种认证方式。
- 通过覆盖配置方法
- 通过为 AuthenticationProvider 实现 bean 实例
我需要知道它们之间有什么区别以及使用它们的优缺点。
1.
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
return daoAuthenticationProvider;
}
解决方案
如果您不确定弹簧安全过滤器链,请参阅此答案。Spring Security 过滤器链是如何工作的
这是我最近在设置演示 ldap + 内存中身份验证时截取的屏幕截图。
如您所见,最后,我们希望
AuthenticationFilter
在我们的 spring 安全过滤器链中添加一个类型。该过滤器负责接收登录请求并决定身份验证是否成功。AuthenticationFilter
引用AuthenticationManger
和AuthenticationManger
实现(称为ProviderManager
)不直接进行身份验证。相反AuthenticationManger
,实现可以有一个AuthenticationProvider
s 列表并取决于类型身份验证请求,它要求AuthenticationProvider
其列表中的对应对象进行身份验证。AuthenticationFilter
委托给AuthenticationManger
(.ieProviderManager
),后者又委托给one
ofAuthenticationProvider
所以这里是样本。仅出于演示目的,我正在复制您的
authenticationProvider()
定义并查看AuthenticationManger
.ie的ProviderManager
外观
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider1())
.authenticationProvider(authenticationProvider2());
}
@Bean("my-auth-provider-1")
public AuthenticationProvider authenticationProvider1(){
DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
return provider;
}
@Bean("my-auth-provider-2")
public AuthenticationProvider authenticationProvider2(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
return provider;
}
笔记
我在这里简化了一点。其实ProviderManager
也可以有父母。但实际上它有一个提供者列表。见https://spring.io/guides/topicals/spring-security-architecture
推荐阅读
- lsof - lsof 显示许多相同的文件,设备名为 0,0
- text - 是否可以在 ffmpeg 中为文本添加笔画?
- angular - 解析参数时如何预期错误?- Angular6,茉莉花
- kubernetes - 如何诊断未生成证书管理器的证书机密?
- amazon-web-services - DynamoDB 中的热分区问题随着新的按需功能而消失了吗?
- reactjs - 如何在带有 webpack 的 React 应用程序中的 web 工作者中使用 ES6 模块?
- javascript - 如何在 React 中自定义 Material UI?
- python - 在循环中跳过多次迭代
- eclipse - Eclipse 等效于 Intellij 动态属性
- python - RuntimeError:CUDA 错误:内存不足 - DCGAN with image_size = 256