Spring Security提示There is no PasswordEncoder mapped for the id "null" 解決辦法

項目開發使用的 Spring Boot 集成到spring security時提示如下錯誤: 

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

    at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:238) ~[spring-security-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
   ........

解決方法:

通過閱讀 Spring Security 的官方文檔,閱讀了一些源碼,用一個簡單實例,以闡述問題的解決辦法。 
1、首先從官方文檔入手,在Spring 官網找到 security 項目(https://spring.io/projects)

關於 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 ”。
解決辦法的示例: 
更正前的用戶認證規則:

    // 自定義配置認證規則
    @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())

    }

問題解決了!
轉載地址https://blog.csdn.net/Hello_World_QWP/article/details/81811462

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