Last updated: 2023-01-19

  1. Learn
  2. Next Steps
  3. Get Authenticated User

Getting the currently authenticated user in Spring Boot

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.

Learn more
or see pricing