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:


Usage example

Change a text:

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

Add a class on html element:

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


  • 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.

      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.

      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.



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


Developed and designed by Netgloo
© 2019 Netgloo