SpringSecurity整合Thymeleaf和后台的权限

发布时间 2023-07-25 11:10:31作者: 与f

1.首先,我们需要在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>

 

2.在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">

 

3.获取属性:我们可以在html页面中通过sec:authentication标签获取usernamePasswordAuthenticationToken中所有getXXX的内容

name :登录账号名称
principal :登录主体,在自定义登录逻辑中是 UserDetails
credentials :凭证
authorities :权限和角色
details :实际上是 WebAuthenticationDetails 的实例。可以获取 remoteAddress (客
户端 ip)和 sessionId (当前 sessionId)

4.sec:authorize可以判断是否含有某权限或角色来显示或隐藏内容,做到权限的安全。

比如:
我们给用户添加以下角色和权限 (后台
UserDetailsServiceImpl的loadUserByUsername方法

//1.按照用户名查用户
//2.按id查权限list
//3.按id查角色list (角色必须前面拼接ROLE_)
//4.把权限list和角色list拼接成一个list,传入User
//User user=new User(username,myUser.getPassword(),authorities);

return new User("admin", encode,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin," +
                        "normal,ROLE_abc,/main.html, /insert, /delete"));

然后,在前端模板中写以下代码来判断权限和角色

<!--如果没认证-->
<div sec:authorize="!isAuthenticated()">显示没认证的内容</div>
<!--如果认证了-->
<div sec:authorize="isAuthenticated()">显示认证的内容</div>

通过权限判断:
<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>

 

 

5.SpringSecurity的后台常用注解

 

 

转 : https://blog.csdn.net/qq_42582773/article/details/121941391

https://blog.csdn.net/weixin_46818691/article/details/126630085