[英]Use Spring Security in Thymeleaf escaped expressions in JavaScript
这在Thymeleaf
3.0 中是可能的:
/*[# th:if="${user.admin}"]*/
alert('Welcome admin');
/*[/]*/
但是,这不起作用:
/*[# sec:authorize="hasAnyRole('ROLE_ADMIN)"]*/
alert('Welcome admin');
/*[/]*/
这真的不可能还是我做错了什么?
我使用 Spring Security 4.1。
关于转义表达式解析的一些背景信息: https : //github.com/thymeleaf/thymeleaf/issues/395
编辑 1
Daniel Fernández 在我最初的问题中发现了一个缺失的单引号。
不幸的是,添加它后,它仍然不起作用。
表达式被解析,因为它从生成的 html/javascript 中消失了。
但是 document.writeln() 即使我没有登录也会被执行,甚至当我登录并且我将检查更改为sec:authorize="hasRole('ROLE_ADMIN123')
<script type="text/javascript" th:inline="javascript">
/*[# sec:authorize="hasRole('ROLE_ADMIN')"]*/
document.writeln("ADMIN !!!");
/*[/]*/
</script>
编辑 2
这是我的解决方法, 直到另行通知:
在@Service
创建一个方法来检查用户是否具有所需的角色:
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
@Service
public class UtilService {
public boolean hasAnyRole(HttpServletRequest req, String... roles) {
for (final String role : roles) {
if (req.isUserInRole(role)) {
return true;
}
}
return false;
}
}
并在JavaScript
块中像这样使用它:
<script type="text/javascript" th:inline="javascript">
/*[# th:if="${@utilService.hasAnyRole(#httpServletRequest, 'ROLE_ADMIN')}"]*/
...
/*[/]*/
</script>
看起来像一个语法错误。 您的sec:authorize="hasAnyRole('ROLE_ADMIN)"
...
我遇到了同样的问题,我只需要更新 thymeleaf 和 thymeleaf-extras-springsecurity4 来提供帮助。
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
这是一个链接
如果您更愿意控制哪个用户或组有权访问特定 JS 文件而不是编写内联 JS,您可以随时在脚本标签中添加 sec:authorize 键。 通过这种方式,您可以将字段、功能和数据封装到一组给定的用户,并在整个项目中保持模板的实用使用。
在这种情况下,我使用 hasAuthority 参数,因为当用户登录我的 Web 应用程序时,我已将组声明附加到我的 JWT。 您显然可以定制它以满足您自己的需求。 使用 Spring5 和 thymeleaf 3 进行测试和工作。
这是我从你的 HTML 中的意思。
<html xmlns:th="http://thymeleaf.org" xmlns="http://www.w3.org/1999/html" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<body></body>
<script type="text/javascript" th:src="@{/js/myJsFile.js}" sec:authorize="${hasAuthority('usersGroup')}"></script>
<script type="text/javascript" th:src="@{/js/myOtherJsFile.js}" sec:authorize="${hasAuthority('adminGroup')}"></script>
这是我的 POM 依赖项:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
我特别希望这样做是为了限制对特定数据库字段的访问以编辑表。 https://editor.datatables.net/manual/security#Privilege-escalation
完整参考: https : //www.thymeleaf.org/doc/articles/springsecurity.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.