SpringSecurity测试登录页面报错There is no PasswordEncoder mapped for the id “null”

SpringSecurity测试登录页面报错There is no PasswordEncoder mapped for the id “null”

 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       // super.configure(auth);
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2","VIP3")
                .and()
                .withUser("wangwu").password("123456").roles("VIP1","VIP3");
    }

结果:
在这里插入图片描述
控制台报错

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
	at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:250) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
	at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:198) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]

什么密码编码映射id为空,网上查到资料:

Spring security 5.0中新增了多种加密方式,也改变了默认的密码格式
现如今Spring Security中密码的存储格式是“{id}…………”.前面的id是加密方式,id可以是bcrypt、sha256等,后面跟着的是加密后的密码.也就是说,程序拿到传过来的密码的时候,会首先查找被“{”和“}”包括起来的id,来确定后面的密码是被怎么样加密的,如果找不到就认为id是null.这也就是为什么我们的程序会报错:There is no PasswordEncoder mapped for the id “null”.官方文档举的例子中是各种加密方式针对同一密码加密后的存储形式,原始密码都是“password”.

解决办法
修改一下configure中的代码,我们要将前端传过来的密码进行某种方式加密,可以用bcrypt加密方式.

1. 在内存中存取密码的修改方式

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  //inMemoryAuthentication 从内存中获取
  auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user1").password(new BCryptPasswordEncoder().encode("123")).roles("USER");
}

inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())",这相当于登陆时用BCrypt加密方式对用户密码进行处理.以前的".password(“123”)" 变成了 “.password(new BCryptPasswordEncoder().encode(“123”))”,这相当于对内存中的密码进行Bcrypt编码加密.如果比对时一致,说明密码正确,才允许登陆.

2. 在数据库中存取密码的修改方式

如果你用的是在数据库中存储用户名和密码,那么一般是要在用户注册时就使用BCrypt编码将用户密码加密处理后存储在数据库中,并且修改configure()方法,加入".passwordEncoder(new BCryptPasswordEncoder())",保证用户登录时使用bcrypt对密码进行处理再与数据库中的密码比对.如下:

//注入userDetailsService的实现类
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());

参考来源:https://blog.csdn.net/zhizhengguan/article/details/103945603

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值