Spring Security 登录报错:There is no

2020-08-13  本文已影响0人  周山

错误描述:

在使用Spring Security 登录报错:There is no PasswordEncoder mapped for the id “null”
解决思路:
我们先测试不连接数据库使用 auth.inMemoryAuthentication()方法从内存中模拟用户账号密码及等级;
发现仍然报错,了解到Spring security 5.0中新增了多种加密方式,使得当进行验证时Spring Security将传输的数据看作是进行了加密后的数据,在匹配之后发现找不到正确识别序列,就认为id是null,因此要将前端传过来的密码进行某种方式加密。

解决办法:

原程序:

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

}

修改后:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //super.configure(auth);
    auth.inMemoryAuthentication()
            .passwordEncoder(new BCryptPasswordEncoder())//登陆时用BCrypt加密方式对用户密码进行处理
            .withUser("zhangsan")
            .password(new BCryptPasswordEncoder().encode("123456"))//对密码进行Bcrypt编码加密
            .roles("VIP1","VIP2")
            .and()
            .withUser("lisi")
            .password(new BCryptPasswordEncoder().encode("123456"))//对密码进行Bcrypt编码加密
            .roles("VIP1","VIP3")
            .and()
            .withUser("wangwu")
            .password(new BCryptPasswordEncoder().encode("123456"))//对密码进行Bcrypt编码加密
            .roles("VIP2","VIP3");

}

补充

如果用的是在数据库中存储用户名和密码,需要要在用户注册时就使用BCrypt编码将用户密码加密处理存储在数据库中。保证用户登录时使用bcrypt对密码进行处理再与数据库中的密码比对。如下:

//在进行用户注册时注入
auth.userRegisterService(userService).passwordEncoder(new BCryptPasswordEncoder());
上一篇下一篇

猜你喜欢

热点阅读