There is no PasswordEncoder mapped for the id "null"

问题描述:

      今天在使用SpringBoot整合spring security 同时整合druid,使用内存进行自定义用户校验得时候,登录时响应但是后台报错: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.accenture.eurekaserver.config;

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

/**
 * @Auther: kzj-js01
 * @Date: 2019/3/1 14:38
 * @Description: MyPasswordEncoder 密码加密处理
 */
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());
    }
}

然后再去认证的时候进行调用去校验密码即可:

package com.accenture.eurekaserver.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @Auther: kzj-js01
 * @Date: 2019/3/1 09:59
 * @Description: Security 配置
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {  //配置策略
//        http.csrf().ignoringAntMatchers("/druid/*");
        http.authorizeRequests()    //授权请求
                .anyRequest().authenticated()   //所有得请求都认证通过 才能访问
                .and()
                .formLogin();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //可以设置内存指定的登录的账号密码,指定角色
        //不加.passwordEncoder(new MyPasswordEncoder())
        //就不是以明文的方式进行匹配,会报错
//        auth.inMemoryAuthentication() .withUser("user").password("123456").roles("ADMIN");
        //.passwordEncoder(new MyPasswordEncoder())。
        //这样,页面提交时候,密码以明文的方式进行匹配。
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user").password("123456").roles("ADMIN");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值