框架环境使用的el-admin,先给我的理解答案:
/**
* @version 1.0
* @description
* 增加#Component("passwordEncoder"),注入名称为passwordEncoder的bean
*/
@Component("passwordEncoder")
public class CustomPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
我看到网上有大量以下的其他答案
/**
* @version 1.0
* @description
*/
public class CustomPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
private final UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
// 密码加密方式
return new CustomPasswordEncoder();
}
//这段代码在WebSecurityConfigurerAdapter中有LazyPasswordEncoder是无效的,即便设置了,也会被冲掉
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
但是很不幸,我的项目中无效,不知道是不是框架问题,但是在正常容器的情况下,应该是通的
如果你也是使用第一段的代码而能够正常使用的,那么恭喜你,以下是我认为的原因
WebSecurityConfigurerAdapter 中子类 LazyPasswordEncoder 负责延迟(懒)加载,以下是部分代码
static class LazyPasswordEncoder implements PasswordEncoder {
private ApplicationContext applicationContext;
private PasswordEncoder passwordEncoder;
LazyPasswordEncoder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) {
return this.passwordEncoder;
} else {
PasswordEncoder passwordEncoder = (PasswordEncoder)this.getBeanOrNull(PasswordEncoder.class);
if (passwordEncoder == null) {
passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
this.passwordEncoder = passwordEncoder;
return passwordEncoder;
}
}
private <T> T getBeanOrNull(Class<T> type) {
try {
return this.applicationContext.getBean(type);
} catch (NoSuchBeanDefinitionException var3) {
return null;
}
}
}
其中注入了环境ApplicationContext ,在环境中获取passwordEncoder,获取到了,就去使用;
如果获取不到那就会使用PasswordEncoderFactories.createDelegatingPasswordEncoder()的方式加载passwordEncoder了,所以我们只需要把passwordEncoder注入到环境中去,就行了。
参考:史诗级的SpringSecurity的认证授权的相关概念及流程讲解!!!_springsecurity授权流程_王菜鸟的博客-CSDN博客
SpringSecurity------WebSecurityConfigurerAdapter配置适配器类 - 建站教程
java - Spring Boot初始化了比预期更多的DaoAuthenticationProviders - IT工具网