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

In this short article, I show you how to get current logged-in username in the 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 in a page with 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.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course