Spring Boot项目配置thymeleaf-extras-
2019-10-18 本文已影响0人
hillside6
项目中使用到Spring Boot Security之后,后台的接口或者页面都加上了权限的校验,但是针对的都是具体的一个操作。实际在开发的过程中,一个页面上的某个功能可能也会存在权限的校验,以简书为例,比如用户没有《写文章》的权限,就可以在整个页面上隐藏该按钮。
后面的讲解默认已经认为你会Spring Boot Security的配置与表达式使用,thymeleaf页面的使用。
在项目配置文件中加入依赖
Maven依赖:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
Gradle依赖:
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'
具体的最新版本号可以根据maven仓库来查询,特别注意的是thymeleaf-extras-springsecurity有3、4、5的版本区别,具体需要看项目使用到的Spring Security版本
thymeleaf-extras-springsecurity3 for integration with Spring Security 3.x
thymeleaf-extras-springsecurity4 for integration with Spring Security 4.x
thymeleaf-extras-springsecurity5 for integration with Spring Security 5.x
页面示例代码如下
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>测试</title>
</head>
<body>
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('USER')">
User
</div>
<div sec:authorize="hasRole('ADMIN')">
Admin
</div>
</body>
</html>
很多网上的教程中都是这样写的,但是实际上是错误的写法
<html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
正确的写法在官方的文档中有的,如下:
<html xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

正确的配置才能让代码有提示,开发事半功倍

注:一定要以官方文档为主,外部的教程只能是参考
https://github.com/thymeleaf/thymeleaf-extras-springsecurity