使用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的实现类。
UserPasswordEncoder.class:
package com.jeffrey.springbootsecurity.config;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @ClassName: UserPasswordEncoder
* @Description: TODO
* @author: jeffrey
* @date: 2018年12月04日
*/
public class UserPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
然后在内存用户中添加:
package com.jeffrey.springbootsecurity.config;
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;
/**
* @ClassName: SpringSecurityConfig
* @Description: TODO
* @author: jeffrey
* @date: 2018年12月04日
*/
@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 UserPasswordEncoder()).withUser("admin").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();
}
@Override
public void configure(WebSecurity web) throws Exception {
//设置静态资源不要拦截
web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
}
}
最后运行:输入账号密码:
image.png
输入账号admin密码:123456,验证成功才显示信息:,如果输入admin/1234567就会报错,重新跳回到登录页面,因为admin的用户我没用 new UserPasswordEncorder进行明文匹配
image.png
网友评论