Reputation: 2637
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?
Upvotes: 0
Views: 661
Reputation: 491
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
Upvotes: 1