如何在 Thymeleaf `sec:authorize` 属性中使用 Spring EL 表达式 [英] How to use Spring EL expressions in Thymeleaf `sec:authorize` attribute

查看:27
本文介绍了如何在 Thymeleaf `sec:authorize` 属性中使用 Spring EL 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

@PreAuthorize(MethodSecurityExpressions.USER)@GetMapping("路径/到/列表")公共字符串列表(模型模型){返回列表";}

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

    <li>...</li>

但是我想做这样的事情,

    <li>...</li>

我使用的是 Spring Boot 1.5.8.我已经通读了 JSP 标签图书馆文档Thymeleaf 文档 并到处搜索但没有找到任何有希望的东西.

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

解决方案

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

类方法安全表达式

package org.example;公共最终类 MethodSecurityExpressions {公共静态最终字符串 USER = "USER";}

来源:

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

I have a class used to store method security expressions.

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

In controllers I've used it like this,

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

In Thymeleaf templates I'm currently doing the following,

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

but I want to do something like this,

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

I'm using Spring Boot 1.5.8. I've read through the JSP tag library documentation and the Thymeleaf documentation and searched all over but not finding anything promising.

Does anyone know if this is possible, or know of a similar way of accomplishing this?

解决方案

The sec:authorize attribute evaluates a Spring Security Expression. This expression is in fact a Spring EL expression evaluated on a SpringSecurity-specific root object. Therefore an adequate solution could look like:

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

Class MethodSecurityExpression

package org.example;

public final class MethodSecurityExpressions {
    public static final String USER = "USER";
}

Sources:

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

这篇关于如何在 Thymeleaf `sec:authorize` 属性中使用 Spring EL 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆