There is no PasswordEncoder mapped for the id "null"的解决办法


今日在SpringBoot项目中使用 Spring Security ,登录时发现报500错,报错信息如下:

There is no PasswordEncoder mapped for the id "null"
  
  
 
 

 我接着查找了前端页面上,发现密码框的name属性确实指定的是 password ,并没有出错。这是怎么回事呢?

于是就上网百度,发现这是由于Spring security5中新增加了加密方式,并把原有的spring security的密码存储格式改了。

去官网查找得知,修改后的密码存储格式为:

{id}encodedPassword
  
  
 
 

于是大概就明白了程序出错的原因: 前端传过来密码后,程序会查找被 花括号"{}"包括起来的id ,以此来确定后面的密码怎么进行加密,而我们在前面并没有按该格式进行处理,这就导致找不到id,就报错了。

明白了报错的原因,就好解决了, 我们只需要对前端传过来的密码进行某种方式加密,就可以了,而官方推荐的是使用bcrypt的加密方式。解决办法如下:

 在Securty配置类SecurtyConfig(继承 WebSecurityConfigurerAdapter)中修改 配置即可。


   
   
  
  
  1. @EnableWebSecurity
  2. public class SecurtyConfig extends WebSecurityConfigurerAdapter {
  3. /**
  4. * 自定义配置
  5. *
  6. * @param http
  7. * @throws Exception
  8. */
  9. @Override
  10. protected void configure(HttpSecurity http) throws Exception {
  11. http.authorizeRequests()
  12. .antMatchers( "/css/**", "/js/**", "/fonts/**", "/index").permitAll() //都可以访问
  13. .antMatchers( "/users/**").hasRole( "ADMIN") //需要相应的角色才能访问
  14. .and()
  15. .formLogin() //基于Form表单登录验证
  16. .loginPage( "/login").failureUrl( "/login-error"); //自定义登录界面
  17. }
  18. /**
  19. * 认证信息管理
  20. * spring5中摒弃了原有的密码存储格式,官方把spring security的密码存储格式改了
  21. *
  22. * @param auth
  23. * @throws Exception
  24. */
  25. @Autowired
  26. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  27. auth.inMemoryAuthentication() //认证信息存储到内存中
  28. .passwordEncoder(passwordEncoder())
  29. .withUser( "user").password(passwordEncoder().encode( "123456")).roles( "ADMIN");
  30. }
  31. private PasswordEncoder passwordEncoder() {
  32. return new BCryptPasswordEncoder();
  33. }
  34. }

主要是需要对 密码进行加密操作,定义的 passwordEncoder() 方法返回一个 BCryptPasswordEncoder对象,对上面的密码进行加密。这样就解决了该问题。

另外  还有一个也可以解决.


   
   
  
  
  1. @Bean
  2. public static PasswordEncoder passwordEncoder(){
  3. return NoOpPasswordEncoder.getInstance();
  4. }

该方法已经过时,不建议使用。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM