關於There is no PasswordEncoder mapped for the id null的報錯

版權聲明:本文爲 小異常 原創文章,非商用自由轉載-保持署名-註明出處,謝謝!
本文網址: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 加密。比對一致,就說明密碼正確,允許登錄。

如果你現在用的也是從內存中取密碼,那麼按照上面這麼修改後應該會成功登錄沒有問題的。



博客中若有不恰當的地方,請您一定要告訴我。前路崎嶇,望我們可以互相幫助,並肩前行!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章