问题描述java
今天在使用SpringBoot整合spring security,使用内存用户验证,但无响应报错:java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" spring
错误缘由app
这是由于Spring boot 2.0.3引用的security 依赖是 spring security 5.X版本,此版本须要提供一个PasswordEncorder的实例,不然后台汇报错误。ide
解决方式ui
建立一个类MyPasswordEncoder 实现PasswordEncoder接口 spa
package com.wang.security.config; import org.springframework.security.crypto.password.PasswordEncoder; 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()); } }
在使用认证的时候用MyPasswordEncoder去校验密码code
@Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //能够设置内存指定的登陆的帐号密码,指定角色 //不加.passwordEncoder(new MyPasswordEncoder()) //就不是以明文的方式进行匹配,会报错 auth.inMemoryAuthentication().withUser("wang").password("123456").roles("ADMIN"); //.passwordEncoder(new MyPasswordEncoder())。 //这样,页面提交时候,密码以明文的方式进行匹配。 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("wang").password("123456").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { //设置登陆,注销,表单登陆不用拦截,其余请求要拦截 http.authorizeRequests().antMatchers("/").permitAll() .anyRequest().authenticated() .and() .logout().permitAll() .and() .formLogin(); //关闭默认的csrf认证 http.csrf().disable(); }