SpringSecurity的用户认证和授权

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())
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小小狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值