一、问题
输入账号密码日志窗口出现以下问题:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:250) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:198) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$LazyPasswordEncoder.matches(WebSecurityConfigurerAdapter.java:592) ~[spring-security-config-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:90) ~[spring-security-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
....
二、分析
项目开发使用的 Spring Boot 版本是2.2.2.RELEASE,对应的Spring Security 版本是5.2.1。
在Spring Security 5.0之前,PasswordEncoder 的默认值为 NoOpPasswordEncoder 既表示为纯文本密码,在实际的开发过程中 PasswordEncoder 大多数都会设值为 BCryptPasswordEncoder ,所以需要对密码进行加密。
三、解决
passwordEncoder()
添加对应的密码编码方式,同时使用new BCryptPasswordEncoder().encode("xxx")
对密码加密,不然会出现Encoded password does not look like BCrypt的错误警告。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin1").password(new BCryptPasswordEncoder().encode("admin1")).roles("ADMIN", "USER") // 管理员,同事具有 ADMIN,USER权限,可以访问所有资源
.and()
.withUser("user1").password(new BCryptPasswordEncoder().encode("user1")).roles("USER")// 普通用户,只能访问 /product/**
.and()
.passwordEncoder(new BCryptPasswordEncoder());
}