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 Security 5.0之前,默认值PasswordEncoder是NoOpPasswordEncoder需要纯文本密码。在Spring Security 5中,默认值为DelegatingPasswordEncoder,这需要密码存储格式。

解决方法:

方法一:- 添加密码存储格式,对于纯文本,添加{noop}

修改配置类代码,在密码前面加{noop}

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
//        super.configure(auth);
        auth.inMemoryAuthentication()
                .withUser("张三").password("{noop}123").roles("vip1","vip2")
                .and()
                .withUser("李四").password("{noop}123").roles("vip1");
    }
方法二:创建MyPasswordEncoder类实现PasswordEncoder,加注解 @Component
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

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

配置类写法:加个.passwordEncoder(new MyPasswordEncoder())

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
//        super.configure(auth);
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("张三").password("123").roles("vip1","vip2")
                .and()
                .withUser("李四").password("123").roles("vip1");
    }

猜你喜欢

转载自blog.csdn.net/JavaSupeMan/article/details/107312755