本文源码已由GitHub https://github.com/2335119327/SpringBootDemo 已经收录,之后会持续更新SpringBoot系列,欢迎Star。
温馨提示:本文章中的动图被压缩后可能不太清晰,可以点击动图鼠标右键在新标签中打开图片就很清晰了。
1、基本环境搭建
项目整体结构
2、登录&认证&授权
导入Serurity依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制授权规则
//antMatchers 路径匹配
//hasRole() 设置角色
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
}
}
可以看见首页可以访问,但其他请求被拒绝,原因:我们设置了角色,但没有登陆
**
设置密码编码
//密码编码 passwordEncoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//定义认证规则
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2")
.and()
.withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3")
.and()
.withUser( BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2","VIP3");
}
可以看见登陆成功,由于我登陆的是zhangsan没有VIP3的权限所以访问报错
3、权限控制&注销
3.1、添加注销功能
在welcome页面添加注销功能
3.2、完善登录用户信息
显示当前登陆的用户信息
导入thymeleaf与security的整合依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<h1 style="text-align: center">欢迎欢迎,热烈欢迎!!!</h1>
<!--!isAuthenticated() 没有登录-->
<div sec:authorize="!isAuthenticated()">
<h2 style="text-align: center">想看资源,请先登录,不要想白嫖。 <a th:href="@{/login}">请登录</a></h2>
</div>
<!--"isAuthenticated() 已登录-->
<div sec:authorize="isAuthenticated()">
<!--sec:authentication="principal.authorities" 读取所有角色-->
<h2><span sec:authentication="name"></span>,您好,您的角色有:<span sec:authentication="principal.authorities"></span></h2>
<form method="post" th:action="@{/logout}">
<input type="submit" value="注销">
</form>
</div>
3.3、根据不同角色显示不同信息
例:sec:authorize=“hasRole(‘VIP1’)” 如果有VIP1权限就显示
<div sec:authorize="hasRole('VIP1')">
<h2>普通资源</h2>
<a th:href="@{/level1/1}">前往普通资源</a>
</div>
<div sec:authorize="hasRole('VIP2')">
<h2>高级资源</h2>
<a th:href="@{/level2/2}">前往高级资源</a>
</div>
<div sec:authorize="hasRole('VIP3')">
<h2>超级资源</h2>
<a th:href="@{/level3/3}">前往超级资源</a>
</div>
5、记住我功能
5、定制登录页
增加记住我功能
本文源码已由 GitHub https://github.com/2335119327/SpringBootDemo 已经收录,之后会持续更新SpringBoot系列,欢迎Star。
觉得博主写的不错的读者大大们,可以点赞关注和收藏哦,谢谢各位!