Last updated: 2023-01-19
Getting the currently authenticated user in Spring Boot
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. 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 getAuthenticedUser
method.
Extension of the UserService to get the JPA entity
In our example the field email
is used as the username. Since our entity is also called User
, we need to fully qualify the Spring Security class org.springframework.security.core.userdetails.User
.
New method call to load the addresses
With this, we can now complete our AccountController
and use the new method. This allows the AddressService
to provide the addresses of the given user.