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

    }

 

posted @ 2019-01-22 16:12  薛定谔病态猫  阅读(2605)  评论(0编辑  收藏  举报