How to find the logged-in user in Spring Boot?

Sometimes we require to access logged-in users in different services of the Spring Boot project.

Spring Boot which uses Spring Security internally provides a SecurityContextHolder class. This class allows the lookup of the currently authenticated user by instantiating an Authentication class as shown below:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

The authentication instance now provides the following methods:

  • Get the username of the logged in user: getPrincipal()
  • Get the password of the authenticated user: getCredentials()
  • Get the assigned roles of the authenticated user: getAuthorities()
  • Get further details of the authenticated user: getDetails()

Example to get logged-in user using SecurityContextHolder class

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Get user name
authentication.getName()

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *