SpringSecurity整合Thymeleaf

3 篇文章 0 订阅
1 篇文章 0 订阅
本文介绍了如何在Spring Boot项目中结合Thymeleaf和Spring Security进行权限控制。通过添加相关依赖,配置Thymeleaf的命名空间和security命名空间,可以在HTML页面动态展示或隐藏内容。利用`sec:authorize`标签,可以根据用户角色和权限来决定按钮的显示。示例展示了如何根据用户角色和权限来控制新增、删除、修改和查看等操作的可见性。
摘要由CSDN通过智能技术生成
  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>
  1. 在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">
  1. 获取属性:我们可以在html页面中通过sec:authentication标签获取usernamePasswordAuthenticationToken中所有getXXX的内容
    name :登录账号名称
    principal :登录主体,在自定义登录逻辑中是 UserDetails
    credentials :凭证
    authorities :权限和角色
    details :实际上是 WebAuthenticationDetails 的实例。可以获取 remoteAddress (客
    户端 ip)和 sessionId (当前 sessionId)
  2. 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权限,所以修改和查看的权限没有显示出来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值