基于内存存储认证信息
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* authentication [ɔːˌθentɪˈkeɪʃn] n. 身份验证; 认证;鉴定;
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中创建一个用户,设置密码和权限
auth.inMemoryAuthentication()
.withUser("devin")
.password("123")
.authorities("ADMIN");
}
}
访问:http://localhost:8080/hello 重定向到登录页面
控制台抛出如下异常
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
问题原因:密码要存储加密后的。
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
// 设置默认的加密方式
return new BCryptPasswordEncoder();
}
/**
* authentication [ɔːˌθentɪˈkeɪʃn] n. 身份验证; 认证;鉴定;
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//对密码加密
final String password = passwordEncoder().encode("123");
//在内存中创建一个用户,设置密码和权限(创建了具体的用户信息以后就不会再生产默认的用户和密码)
auth.inMemoryAuthentication()
.withUser("devin")
.password(password)
.authorities("ADMIN");
}
}
访问:http://localhost:8080/hello 重定向到登录页面
登录成功以后,重定向回原来的请求