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:
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
Now we can refer to the principal in the HTML page using the sec:authorize attribute:
<html xmlns:th="https://www.thymeleaf.org"
  xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
    <div sec:authorize="isAuthenticated()">Authenticated as <span sec:authentication="name"></span></div>
</body>
</html>
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.


Comments