解决java.lang.IllegalArgumentException: There is no PasswordEncoder mapped f...
解决java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id使用springboot,权限管理使用spring security,使用内存用户验证,但无响应报错:java.lang.IllegalArgumentException: There is no PasswordEncoder ma
解决java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id
使用springboot,权限管理使用spring security,使用内存用户验证,但无响应报错:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
解决方法:
这是因为Spring boot 2.0.3引用的security 依赖是 spring security 5.X版本,此版本需要提供一个PasswordEncorder的实例,否则后台汇报错误:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
并且页面毫无响应。
因此,需要创建PasswordEncorder的实现类。
MyPasswordEncoder.class:
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()); } }
然后在内存用户中添加:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //可以设置内存指定的登录的账号密码,指定角色 //不加.passwordEncoder(new MyPasswordEncoder()) //就不是以明文的方式进行匹配,会报错 auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN"); //.passwordEncoder(new MyPasswordEncoder())。 //这样,页面提交时候,密码以明文的方式进行匹配。 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("cxh").password("cxh").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(); } @Override public void configure(WebSecurity web) throws Exception { //设置静态资源不要拦截 web.ignoring().antMatchers("/js/**","/cs/**","/images/**"); } }
最后运行:输入账号cxh密码:cxh,验证成功才显示信息:,如果输入admin/123456就会报错,重新跳回到登录页面,因为admin的用户我没用 new MyPasswordEncorder进行明文匹配
更多推荐
所有评论(0)