【问题标题】:Different Thymeleaf layout decorators based on different Spring Securirty roles基于不同 Spring Security 角色的不同 Thymeleaf 布局装饰器
【发布时间】:2020-10-15 16:35:31
【问题描述】:

我有两个用户角色和一个布局页面,以及一个 .html,其中包含主要内容的布局片段,可供两个用户访问。我想根据用户使用特定的布局页面。

这就是我想要做的:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
    layout:decorate="~{(hasRole('ADMIN') ? adminLayout : customerLayout)}">

<head>...</head>
<body>
    <th:block layout:fragment="someContent">
        <h1>Same main content but replacing layout depending of the user!</h1>
        ....
    </th:block>
</body>

</html>

但我不断收到页面评估失败或 hasRole 方法不存在的错误,具体取决于我尝试的语法:

org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method hasRole(java.lang.String) cannot be found on type org.thymeleaf.spring5.expression.SPELContextMapWrapper

是否可以根据.html 文件中(不在控制器等中)中经过身份验证的用户角色来确定使用的布局装饰器?或者更确切地说,是否可以从这样的范围内访问这些安全方法?

【问题讨论】:

    标签: spring-mvc spring-security thymeleaf


    【解决方案1】:

    你必须参考spring security提供的utility bean,thymeleaf才能调用spring security方法。

    调用 spring 安全方法是在实用程序 bean 提供的方法 expression 中完成的,它的返回类型是布尔值。所以你的代码会是这样的:

    layout:decorate="~{#authorization.expression('hasRole(''ADMIN'')') ? 'adminLayout' : 'customerLayout'}"
    

    【讨论】:

    • 我必须在表达式周围加上${},但它有效,谢谢!
    • 对于未来的用户,这就是@g-otn 的意思layout:decorate="~{${#authorization.expression('hasRole(''ADMIN'')') ? 'adminLayout' : 'customerLayout'}}"&gt;
    猜你喜欢
    • 2014-10-19
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2020-04-10
    • 2020-12-18
    • 1970-01-01
    • 2018-05-27
    • 2021-06-01
    相关资源
    最近更新 更多