Spring Security - How to Get Current Logged-In Username in Themeleaf

In this short article, I show you how to get a current logged-in username in Themeleaf using Spring Security.
Thymeleaf is a modern, server-side web templating engine, with good integration with the Spring MVC framework. Let’s see how to access the currently authenticated principal on a page with the Thymeleaf engine.

How to Get Current Logged-In Username in Themeleaf using Spring Security

First, we need to add the thymeleaf-spring5 and the thymeleaf-extras-springsecurity5 dependencies to integrate Thymeleaf with Spring Security:
Now we can refer to the principal in the HTML page using the sec:authorize attribute:
<html xmlns:th="https://www.thymeleaf.org"
    <div sec:authorize="isAuthenticated()">Authenticated as <span sec:authentication="name"></span></div>
In the above code, The sec:authorize attribute renders an element’s content when its expression evaluates to true. The sec:authentication attribute gets the currently logged-in principle or user name.