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

I know how to use sec:authentication="name" and sec:authorize="hasAnyRole(...)" and create the result using my own HTML tag, but now I want to use them in an expression, for example:

 th:if="${hasAnyRole('ROLE_USER', 'ROLE_ADMIN') and someotherboolexpression}" 

Is there any way to do this?

+6
source share
1 answer

Using the thymeleaf-extras-springsecurity , you can use the Spring security authorization expression inside th:if using the #authorization expression utility #authorization .

 <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 sec:authentication and sec:authorize as if you were using a 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 add a dialect to your template 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> 
+10
source

All Articles