欢迎浏览我的博客 获得更多精彩文章
https://boyn.top
场景
Spring Boot VERSION : 2.1.5
Spring Security VERSION : 5.1.5
在Spring Security的开发中,我们需要继承WebSecurityConfigurerAdapter来配置一个SpringSecurityConfig的配置类,相信很多人都是从这里开始的.然后我们会设置一些存放在内存中的账户,并且指定他们的角色,如以下方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
}
我们指定了一个admin用户,密码为123456.
当我们运行这个项目时,登录 localhost:8080/…时,会跳到一个登录页面,但是输入了用户密码之后,却没办法跳转到之前的页面,并且查看IDE,其中报出了以下的错误
异常说明
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null”
at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:244) ~[spring-security-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:198) ~[spring-security-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
后面还有一些先省略不表,我们在这个异常中,可以看到主要原因是: There is no PasswordEncoder mapped for the id “null”
即我们在对密码进行编码的时候没有指定对应的密码编码器.
这个原因是由于在spring security4中,默认的密码编码器是 NoOpPasswordEncoder ,要求密码是纯文本,并且在内存中不会加密存储,
而到了spring security5时,默认的密码编码器变成了DelegatingPasswordEncoder,它要求密码存储时,要指定加密格式,这个在官网的spring security5刚发布时,写入了release文档中(见参考链接)
密码的存储需要进行编码,所以需要添加编码格式,spring Security框架已经为我们定制好了一些默认编码器,我们只需要在代码中声明即可
出错部分代码
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");//基于内存管理的角色授权登录系统
}
}
更改方法
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("ADMIN");//基于内存管理的角色授权登录系统
}
}
指定了NoOpPasswordEncoder进行编码
More
根据官网的介绍,我们可以使用以下的声明方式进行不同的编码
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG (1) {noop}password (2) {pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc (3) {scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc= (4) {sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0 (5)
参考链接
https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-format
https://www.mkyong.com/spring-boot/spring-security-there-is-no-passwordencoder-mapped-for-the-id-null/
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#pe-dpe