Thymeleaf: check if the user is authenticated with Spring Security

In Thymeleaf, using the Spring Security integration module, the following expression returns true if the current user (i.e. the user viewing the page) is authenticated, false otherwise:

${#authorization.expression('isAuthenticated()')}

Usage example

Change a text:

<span th:text="${#authorization.expression('isAuthenticated()')} ? 
               'the user is logged in' : 
               'the user is NOT logged in'">
</span>

Add a class on html element:

<span th:classappend="${#authorization.expression('isAuthenticated()')} ? 'active'"
</span>

References

https://github.com/thymeleaf/thymeleaf-extras-springsecurity
http://www.thymeleaf.org/doc/articles/springsecurity.html

  • rohtakdev

    How do we check if current user is admin ?

    • Check links under References, you should find something useful.
      Like this (from the second reference):

      <div sec:authorize="hasRole('ROLE_ADMIN')">
      This content is only shown to administrators.
      </div>

      or this one (from the first one):

      <div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
      This will only be displayed if authenticated user has role ROLE_ADMIN.
      </div>

      Let us know if you make a try.

      • rohtakdev

        Sweet worked thanks

  • dima
    • Yes, thank you.

      Note that the code in the post above allow you also to do a check inside an attribute, for example if you want to add a class with th:classappend.

  • Soumyajyoti Das

    How to check user with no role..!!
    Actually I want to show some instruction to the user with no role.

    Thanks.

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2016 Netgloo