【问题标题】:How to use Spring EL expressions in Thymeleaf `sec:authorize` attribute如何在 Thymeleaf `sec:authorize` 属性中使用 Spring EL 表达式
【发布时间】:2018-06-05 08:31:23
【问题描述】:

我有一个用于存储方法安全表达式的类。

public final class MethodSecurityExpressions {
    public static final String USER = "hasRole('USER')";
}

在控制器中我是这样使用的,

@PreAuthorize(MethodSecurityExpressions.USER)
@GetMapping("path/to/list")
public String list(Model model) {
    return "list";
}

在 Thymeleaf 模板中,我目前正在执行以下操作,

<ul sec:authorize="hasRole('USER')">
    <li>...</li>
</ul>

但我想做这样的事情,

<ul sec:authorize="#{MethodSecurityExpressions.USER}">
    <li>...</li>
</ul>

我使用的是 Spring Boot 1.5.8。我已经阅读了JSP tag library documentationThymeleaf documentation 并搜索了所有内容,但没有找到任何有希望的内容。

有谁知道这是否可能,或者知道实现此目的的类似方法吗?

【问题讨论】:

    标签: java spring spring-mvc spring-security thymeleaf


    【解决方案1】:

    sec:authorize 属性评估 Spring 安全表达式。这个表达式实际上是在 SpringSecurity 特定的根对象上评估的 Spring EL 表达式。因此,一个适当的解决方案可能如下所示:

    <div sec:authorize="${hasRole('#{T(org.example.MethodSecurityExpressions).USER)}'">
    </div>
    

    类 MethodSecurityExpression

    package org.example;
    
    public final class MethodSecurityExpressions {
        public static final String USER = "USER";
    }
    

    来源:

    https://github.com/thymeleaf/thymeleaf-extras-springsecurity https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/html/expressions.html

    【讨论】:

    • 我使用带有 Thymeleaf 3.0.12 的 Spring Boot 2.4.4 进行了尝试,但它不起作用。表达式是否完全正确,因为表达式中的括号似乎不平衡?
    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 2016-03-18
    • 2019-10-05
    • 2021-02-23
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多