关于There is no PasswordEncoder mapped for the id null的报错

    技术2022-07-10  133

    版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢! 本文网址:https://blog.csdn.net/sun8112133/article/details/107056906

    最近在做 Spring Boot + Spring Security 登录认证的时候,我已经在认证策略配置的认证信息管理方法中配置了一个身份信息,而且在登录页面中用户名和密码输入完全正确的情况下,却一直在报 There is no PasswordEncoder mapped for the id null 的错误。经过网上查询相关资料才知问题所在,特此总结,如果能帮助到你那就再好不过了。


    报错信息

    java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"


    报错原因及解决方式

    在认证策略配置中的认证信息管理方法里我是这样配置的:

    @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("123").roles("ADMIN"); }

    结果导致了一直在报上面那个错误,后来才知这是因为在 Spring Security 5.0 中新增了多种加密方式,也改变了密码的格式。

    Spring Security 官方推荐的是使用 BCrypt 加密方式。在这里我不得不说一下 MD5 加密现在已经弱爆了,目前 最新版的 Spring Security 中已经把 MD5 剔除了,MD5 太不安全了,更推荐用 BCrypt 加密,而且什么盐值加密也很少用,因为 BCrypt 中已经将 salt 加进去了。

    那么如何对密码加密呢,只需要在 configure() 方法里面指定一下。修改后是这样的:

    @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder(new BCryptPasswordEncoder()) .withUser("admin") .password(new BCryptPasswordEncoder().encode("123")) .roles("ADMIN"); }

    我们从上面的方法中不难看出:在 inMemoryAuthentication() 方法后面多了 .passwordEncoder(new BCryptPasswordEncoder()) ,这相当于登录时就要求用 BCrypt 加密方式对用户密码进行处理。以前的 .password("123456") 也变成了 .password(new BCryptPasswordEncoder().encode("123")) ,这相当于对内存中的密码也进行 BCrypt 加密。比对一致,就说明密码正确,允许登录。

    如果你现在用的也是从内存中取密码,那么按照上面这么修改后应该会成功登录没有问题的。

    博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!
    Processed: 0.009, SQL: 10