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 Dependency

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





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 sec:authorize="isAnonymous()"> 
    <a class="btn btn-success" th:href="@{/login}">Login</a>
    <a class="btn btn-primary" th:href="@{/register}">Register</a>  


Logged in navbar

Logged in navbar

Anonymous user navbar

Anonymous user navbar