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

問題描述java

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

錯誤緣由app

這是由於Spring boot 2.0.3引用的security 依賴是 spring security 5.X版本,此版本須要提供一個PasswordEncorder的實例,不然後臺彙報錯誤。ide

解決方式ui

建立一個類MyPasswordEncoder 實現PasswordEncoder接口 spa

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去校驗密碼code

@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();

    }
相關文章
相關標籤/搜索