SpringSecurity的用户认证和授权
利用三个类:
1. WebSecurityConfigurerAdapter 自定义安全策略
2. @EnableWebSecurity 成功托管
3. AuthenticationManagerBuilder 用来自定义认证策略
创建一个config类
/**
* 先继承一个 WebSecurityConfigurerAdapter 自定义安全策略
*/
//@EnableWebSecurity托管给spring
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
//http策略
//安全过滤 配置 链式编程
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页需要有权限的人
/**
* http下 授权请求authorizeRequests
* permitAll 都可以访问
* hasRole 只有某些权限可以
*/
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
/**
* 如果没有授权 会自动走到 安全security中的官方 login页面
*/
http.formLogin();
}
/**
* 认证,在springboot 2.1.x可以直接使用
* 密码编码:passwordEncoding
* 在Spring Security 5.0+ 新增了很多的加密方法
*
* passwordEncoder增加设置编码
*/
//AuthenticationManagerBuilder 身份认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//内存认证 (正常应该从数据库里读)
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("wjm").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
//数据库认证
//auth.jdbcAuthentication();
}
}
1.认证 正常情况下,没有进行加密的密码 进行登录
2. 增加密码编码
增加设置编码
passwordEncoder(new BCryptPasswordEncoder())