I know how to use sec:authentication="name"
and sec:authorize="hasAnyRole(...)"
and produce a result on their own HTML tag, but now I want to use them in an expression such as:
th:if="${hasAnyRole('ROLE_USER', 'ROLE_ADMIN') and someotherboolexpression}"
Is there a way of doing this?
Using thymeleaf-extras-springsecurity
module, you can use Spring security's authorization expression inside th:if
using the #authorization
expression utility object.
<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')') and #authorization.expression('...') }">
This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>
In fact the dialects added by this new module use sec
as the default prefix so you can use the sec:authentication
and sec:authorize
as if you are using the tag library.
<div sec:authorize="hasRole('ROLE_ADMIN')">
This will only be displayed if authenticated user has role ROLE_ADMIN.
</div>
<div sec:authentication="name">
The value of the "name" property of the authentication object should appear here.
</div>
All you have to do is to add the dialect to your template engine configuration
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
...
<property name="additionalDialects">
<set>
<!-- Note the package would change to 'springsecurity3' if you are using that version -->
<bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
</set>
</property>
...
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With