Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sec:[something] in a thymeleaf expression?

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?

like image 565
DiegoSahagun Avatar asked Feb 01 '16 14:02

DiegoSahagun


1 Answers

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>
like image 121
Bnrdo Avatar answered Oct 21 '22 18:10

Bnrdo