There is no PasswordEncoder mapped for the id “null” 的解决办法
关于 Spring Security 5.0.X 的说明:
在Spring Security 5.0之前,PasswordEncoder 的默认值为 NoOpPasswordEncoder 既表示为纯文本密码,在实际的开发过程中 PasswordEncoder 大多数都会设值为 BCryptPasswordEncoder ,但是这样会导致几个问题:
1、在应用程序中使用 BCryptPasswordEncoder 编码方式编码后的密码,很难轻松的迁移;
2、密码存储后,会再次被更改;
3、作为一个应用中的安全框架,Spring Security 不能频繁地进行中断更改;
在 Spring Security 5.0.x 以后,密码的一般格式为:{ID} encodedPassword ,ID 主要用于查找 PasswordEncoder 对应的编码标识符,并且encodedPassword 是所选的原始编码密码 PasswordEncoder。ID 必须书写在密码的前面,开始用{,和 结束 }。如果 ID 找不到,ID 则为null。例如,在相关的源码中,我找到了 Spring Security 定义的不同的编码方式的列表 ID。所有原始密码都是“ password ”。
更改之前:
// 自定义配置认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("zhangsan").password("12345").roles("SuperAdmin")
.and()
.withUser("lisi").password("12345").roles("Admin")
.and()
.withUser("wangwu").password("12345").roles("Employee");
}
新建一个 PasswordEncoder 并实现 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());
}
}
在用户认证规则中添加自定义的 PasswordEncoder 实例,具体内容如下:
// 自定义配置认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("zhangsan").password("12345").roles("SuperAdmin")
.and()
.withUser("lisi").password("12345").roles("Admin")
.and()
.withUser("wangwu").password("12345").roles("Employee")
.and()
.passwordEncoder(new CustomPasswordEncoder())
}