If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
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.
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
Spring Security - Roles and Privileges
Spring Security β Reset Your Password
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.
http://localhost:8080/spring-security-rest-custom/foos/1
