Spring Security 5 报 There is no PasswordEncoder mapped for the id "null"

今天在学习Spring Security时,登录的时候遇见如下错误:

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

原因是因为在Spring Security 版本 5.0之后,官方新增加了加密方式,并把原有的spring security的密码存储格式改了。

解决方法:

在 Spring Security的配置类中增加如下代码:

    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 将认证信息存储到内存中
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("admin")
                .password(passwordEncoder().encode("123456"))
                .roles("ADMIN");
    }

补充一句:

新的密码存储格式为:加密方式和加密后的密码

{id}encodedPassword

具体存储方式可以查看 PasswordEncoderFactories

 public static PasswordEncoder createDelegatingPasswordEncoder() {
        String encodingId = "bcrypt";
        Map encoders = new HashMap();
        encoders.put(encodingId, new BCryptPasswordEncoder());
        encoders.put("ldap", new LdapShaPasswordEncoder());
        encoders.put("MD4", new Md4PasswordEncoder());
        encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
        encoders.put("noop", NoOpPasswordEncoder.getInstance());
        encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
        encoders.put("scrypt", new SCryptPasswordEncoder());
        encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
        encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
        encoders.put("sha256", new StandardPasswordEncoder());
        return new DelegatingPasswordEncoder(encodingId, encoders);
    }

    private PasswordEncoderFactories() {
    }

之前的默认配置已经被废弃了,不推荐使用!

@Bean
PasswordEncoder passwordEncoder(){
    return NoOpPasswordEncoder.getInstance();
}

你可能感兴趣的:(Spring Security 5 报 There is no PasswordEncoder mapped for the id "null")