Check for Logged in User with Thymeleaf and Spring Security 4

Thymeleaf is a server-side Java templating engine commonly used in web applications that utilize the Spring framework.    

In this article, we'll cover how to detect if a user is logged in.

This is particularly useful for displaying different content on unsecured pages based on authenticated status. On a public landing page, we could show the My Account button instead of the Login and Register buttons.

Add thymeleaf-extras-springsecurity4

We'll need to add the following dependency to our project:

Maven

<dependency>
  <groupId>org.thymeleaf.extras</groupId>
  <artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

Gradle

compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4')

Spring Security dialect in HTML template

The sec:authorize attribute renders an element's content when its expression evaluates to true.

<div class="navbar-form navbar-right"> 
  
  <div sec:authorize="isAuthenticated()"> 
    <a class="btn btn-success"th:href="@{/dashboard}">Dashboard</a> 
  </div> 
  
  <div sec:authorize="isAnonymous()"> 
    <a class="btn btn-success" th:href="@{/login}">Login</a>
    <a class="btn btn-primary" th:href="@{/register}">Register</a>  
  </div>
  
</div>

Output

Logged in navbar

Logged in navbar

Anonymous user navbar

Anonymous user navbar