Last updated: 2023-02-02
Getting the currently authenticated user in Spring Boot
Create your customized Spring Boot prototype with database schema, Thymeleaf, jte, Angular or React frontend and much more - best practices included. ♥
Discover more
After our application has been protected using Spring Security, we have sections that are only accessible for authenticated users. For example, this could be a MyAccount area or a REST endpoint for retrieving the current user's stored addresses. How can we get the JPA entity of the current user in this context?
Frontend controller accessible only for ROLE_USER
The Spring Security Authentication object is accessible directly from the static context. To get the current JPA entity from the database we can create or extend a UserService and add the getAuthenticatedUser method.
Extension of the UserService to get the JPA entity
HttpUserDetails is an extension of the Spring Security class org.springframework.security.core.userdetails.User so the users primary key is also available - which we use here for reading the actual User entity from the database. An authenticated user is always expected to be present.
Adding a utility class with isLoggedIn
Another utility class may come handy if we have areas in our application that are accessible by both authenticated and anonymous users. In this case the UserUtils.isLoggedIn() check should come first before trying to call getAuthenticatedUser(). As our AccountController was already restricted, this is not required and we can simply complete our call.
New method call to load the addresses
This extension allows the AddressService to provide the addresses of the currently authenticated user.