- 首先,我们需要在pom文件中添加以下依赖:
<!--thymeleaf springsecurity5 依赖-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 在html页面中引入thymeleaf命名空间和security命名空间。
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extrasspringsecurity5">
- 获取属性:我们可以在html页面中通过sec:authentication标签获取usernamePasswordAuthenticationToken中所有getXXX的内容
name :登录账号名称
principal :登录主体,在自定义登录逻辑中是 UserDetails
credentials :凭证
authorities :权限和角色
details :实际上是 WebAuthenticationDetails 的实例。可以获取 remoteAddress (客
户端 ip)和 sessionId (当前 sessionId) - sec:authorize可以判断是否含有某权限或角色来显示或隐藏内容,做到权限的安全。
比如:
我们给用户添加以下角色和权限
return new User("admin", encode,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin," +
"normal,ROLE_abc,/main.html, /insert, /delete"));
然后,在前端模板中写以下代码来判断权限和角色
通过权限判断:
<button sec:authorize="hasAuthority('/insert')">新增</button>
<button sec:authorize="hasAuthority('/delete')">删除</button>
<button sec:authorize="hasAuthority('/update')">修改</button>
<button sec:authorize="hasAuthority('/select')">查看</button>
<br/>
通过角色判断:
<button sec:authorize="hasRole('abc')">新增</button>
<button sec:authorize="hasRole('abc')">删除</button>
<button sec:authorize="hasRole('abc')">修改</button>
<button sec:authorize="hasRole('abc')">查看</button>
然后,页面上显示:
正是因为当前用户含有abc角色以及/insert和/delete权限,所以修改和查看的权限没有显示出来