Search code examples
thymeleaf

how to compare the answer of authority.getAuthority() with a specific role 'ROLE_ADMIN' in thymeleaf?


I have tried the code below, but getting false even for ROLE_ADMIN

<th:block th:each="authority : ${#authentication.getAuthorities()}">
     <span  th:with="role=${authority.getAuthority()}">
         <span th:text="${role}"></span>
         <p th:with="res=${#strings.toString(role) == 'ROLE_ADMIN'}">
            <div th:if="${res}">successtrial</div>
            <div th:unless="${res}">failed trial</div>
            <span th:text=${res}></span>
     </span>
        </p>      
</th:block>

Getting ${role} - printed correct, but finally getting failed trial


Solution

  • You can use the hasRole method like this:

    <div sec:authorize="hasRole('ADMIN')">
      <div>success trial</div>
    </div>
    <div sec:authorize="!hasRole('ADMIN')">
      <div>failed trial</div>
    </div>
    

    Be sure to have the org.thymeleaf.extras:thymeleaf-extras-springsecurity5 dependency in your application.