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


問題描述

今天在使用SpringBoot整合spring security,使用內存用戶驗證,但無響應報錯:java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" 

錯誤原因

這是因為Spring boot 2.0.3引用的security 依賴是 spring security 5.X版本,此版本需要提供一個PasswordEncorder的實例,否則后台匯報錯誤。

解決方式

創建一個類MyPasswordEncoder 實現PasswordEncoder接口 

package com.wang.security.config;

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

在使用認證的時候用MyPasswordEncoder去校驗密碼

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //可以設置內存指定的登錄的賬號密碼,指定角色
        //不加.passwordEncoder(new MyPasswordEncoder())
        //就不是以明文的方式進行匹配,會報錯
        auth.inMemoryAuthentication().withUser("wang").password("123456").roles("ADMIN");
        //.passwordEncoder(new MyPasswordEncoder())。
        //這樣,頁面提交時候,密碼以明文的方式進行匹配。
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("wang").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //設置登錄,注銷,表單登錄不用攔截,其他請求要攔截
        http.authorizeRequests().antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().permitAll()
                .and()
                .formLogin();
        //關閉默認的csrf認證
        http.csrf().disable();

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM