Retrieve User Information in Spring Security

1. Overview

This article 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 – programmatic access, first.

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 – decreased testability of the code being one of the more obvious. Instead, we’ll explore alternative solutions for this very common requirement.

3. Get the User in a Controller

In a @Controller annotated bean, there are additional options. The principal can be defined directly as a method argument and it will be correctly resolved by the framework:

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

Alternatively, we can also use the authentication token:

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    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());

And finally, directly from the HTTP request:

@Controller
public class GetUserWithHTTPServletRequestController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }
}

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 @Controller 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:

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

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple() {
        Authentication authentication = authenticationFacade.getAuthentication();
        return authentication.getName();
    }
}

5. Get the User in JSP

The currently authenticated principal can also be accessed in JSP pages, by leveraging the spring security taglib support. First, we need to define the tag in 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 in a page with Thymeleaf engine.

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>

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 implementation of these examples can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is. When the project runs locally, the homepage HTML can be accessed at:

http://localhost:8080/spring-security-rest-custom/foos/1

Related posts:

Quick Guide to Spring MVC with Velocity
Java Program to Implement Sorted Doubly Linked List
Spring Boot - Twilio
Static Content in Spring WebFlux
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Java Program to Implement Randomized Binary Search Tree
Java Program to Implement Interval Tree
Java Program to Implement ArrayDeque API
Java Program to Implement Singly Linked List
Feign – Tạo ứng dụng Java RESTful Client
Returning Custom Status Codes from Spring Controllers
Hướng dẫn sử dụng Java Annotation
Get the workstation name or IP
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Spring Autowiring of Generic Types
Spring Boot - Enabling HTTPS
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
So sánh ArrayList và LinkedList trong Java
Jackson Exceptions – Problems and Solutions
Java Program to Implement RoleList API
Tránh lỗi NullPointerException trong Java như thế nào?
Logout in an OAuth Secured Application
Luồng Daemon (Daemon Thread) trong Java
Case-Insensitive String Matching in Java
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
New in Spring Security OAuth2 – Verify Claims
Converting Strings to Enums in Java
REST Web service: Upload và Download file với Jersey 2.x
Hướng dẫn Java Design Pattern – Builder
An Intro to Spring Cloud Task
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Servlet 3 Async Support with Spring MVC and Spring Security