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 ”。

源码中定义的全部编码方式的列表 ID 如下图:
这里写图片描述

解决办法的示例:
更正前的用户认证规则:

    // 自定义配置认证规则
    @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())

    }

一般即可解决问题


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值