Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

This tutorial will show how to retrieve the user details in Spring Security.

The currently authenticated user is available through a number of different mechanisms in Spring. Let’s cover the most common solution first — programmatic access.

Further reading:

Keep Track of Logged in Users With Spring Security

A quick guide to track logged in users in an application built using Spring Security.

Spring Security - Roles and Privileges

How to map Roles and Privileges for a Spring Security application: the setup, the authentication and the registration process.

Spring Security – Reset Your Password

Every app should enable users to change their own password in case they forget it.

2. Get the User in a Bean

The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

An improvement to this snippet is first checking if there is an authenticated user before trying to access it:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUserName = authentication.getName();
    return currentUserName;
}

There are, of course, downsides to having a static call like this and decreased testability of the code is one of the more obvious. Instead, we’ll explore alternative solutions for this very common requirement.

3. Get the User in a Controller

We have additional options in a @RestController annotated bean.

We can define the principal directly as a method argument, and the framework will correctly resolve it:

@RestController
public class GetUserWithPrincipalController {

    @GetMapping(value = "/username")
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

Alternatively, we can also use the authentication token:

@RestController
public class GetUserWithAuthenticationController {

    @GetMapping(value = "/username")
    public String currentUserName(Authentication authentication) {
        return authentication.getName();
    }
}

The API of the Authentication class is very open so that the framework remains as flexible as possible. Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());

Also, here’s directly from the HTTP request:

@RestController
public class GetUserWithHTTPServletRequestController {

    @GetMapping(value = "/username")
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }
}

Finally, we can use the @AuthenticationPrincipal annotation to get the currently authenticated user details:

@RestController
public class GetUserWithAuthenticationPrincipalAnnotationController {
    
    @GetMapping("/user")
    public String getUser(@AuthenticationPrincipal UserDetails userDetails) {
        return "User Details: " + userDetails.getUsername();
    }
}

Here, the @AuthenticationPrincipal annotation injects the currently authenticated user’s UserDetails into the method. This annotation helps resolve Authentication.getPrincipal() to a method argument.

Additionally, when we annotate a method parameter with @AuthenticationPrincipal, Spring Security automatically provides the principal of the currently authenticated user. The principal represents the user’s identity, which can be the username, a user object, or any form of user identification.

4. Get the User via a Custom Interface

To fully leverage the Spring dependency injection and be able to retrieve the authentication everywhere, not just in @RestController beans, we need to hide the static access behind a simple facade:

public interface IAuthenticationFacade {
    Authentication getAuthentication();
}
@Component
public class AuthenticationFacade implements IAuthenticationFacade {

    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}

The facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable:

@RestController
public class GetUserWithCustomInterfaceController {
    @Autowired
    private IAuthenticationFacade authenticationFacade;

    @GetMapping(value = "/username")
    public String currentUserNameSimple() {
        Authentication authentication = authenticationFacade.getAuthentication();
        return authentication.getName();
    }
}

5. Get the User in JSP

We can access the currently authenticated principal from JSP pages by leveraging the Spring Security Taglib support.

First, we need to define the tag on the page:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Next, we can refer to the principal:

<security:authorize access="isAuthenticated()">
    authenticated as <security:authentication property="principal.username" /> 
</security:authorize>

6. Get the User in Thymeleaf

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.

First, we need to add the thymeleaf-spring6 and the thymeleaf-extras-springsecurity6 dependencies to integrate Thymeleaf with Spring Security:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring6</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>

7. Conclusion

This article showed how to get the user information in a Spring application, starting with the common static access mechanism, followed by several better ways to inject the principal.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
http://localhost:8080/spring-security-rest-custom/foos/1
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW