前言
使用的是spring security自带的login页面,结果登陆的时候,用户名和密码正确也无法打开资源,还是停留在login页面。而且发现控制台报了异常——There is no PasswordEncoder mapped for the id “null”。网上百度了一下发现这是因为Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
{id}encodedPassword
前面的id是加密方式,id可以是bcrypt、sha256等,后面跟着的是加密后的密码。也就是说,程序拿到传过来的密码的时候,会首先查找被“{}”包括起来的id,来确定后面的密码是被怎么样加密的,如果找不到就认为id是null。这也就是为什么我们的程序会报错:There is no PasswordEncoder mapped for the id “null”。
然后修改代码:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("admin");
}
接着又无法登陆,看控制台报错:
Encoded password does not look like BCrypt
因为在spring boot 2.x没有默认的加密器了,所以需要我们注入bean。
/**
* 加密器 spring boot 2.x没有默认的加密器了
*
* @return PasswordEncoder
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
然后登陆发现可以正常登录了。