Search code examples
spring-boottwitter-bootstrapspring-securitythymeleaf

Spring boot Application with Thymeleaf. Using Constants to check hasAuthority


Defined constants in my class and using in UI to validate if user have the authority, show the menu to user else hide it. refer below code the way I implemented.

<li sec:authorize="hasAuthority('${T(com.sample.application.security.Privilege).ADMIN}')" class="nav-item" th:classappend="${template} == 'Home' ? 'active':''">

However, its not working as I expect. I was expecting thymeleaf to transform ${T(com.sample.application.security.Privilege).ADMIN} to ADMIN and verify it as hasAuthority('ADMIN') but thats not working. Is there any other way to do this validation in thymeleaf. Whats the best approach to get this implemented?

Update: Tried with assigning the constants to thymeleaf local variable as well. Didnt work either.

<ul class="navbar-nav" th:with="admin=${T(com.sample.application.security.Privilege).ADMINISTRATOR}, groupAdmin=${T(com.sample.application.security.Privilege).APPLICATION_GROUP_ADMIN}, basicUser=${T(com.sample.application.security.Privilege).APPLICATION_BASIC_USER}" >
                <li sec:authorize="hasAuthority(${basicUser}) OR hasAuthority(${admin})" class="nav-item" th:classappend="${template} == 'home' ? 'active':''">
                    <a class="nav-link" href="/myApplication/User">Customer Home</a>
                </li>......</ul>

Solution

  • After trying several ways. Below solution worked without any issue.

    <ul class="navbar-nav">
    <li sec:authorize="${hasAuthority(T(com.sample.application.security.Privilege).ADMINISTRATOR) OR hasAuthority(T(com.sample.application.security.Privilege).APPLICATION_GROUP_ADMIN)}" class="nav-item" th:classappend="${template} == 'home' ? 'active':''">
        <a class="nav-link" href="/myApplication/User">Customer Home</a>
    </li>