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

How to find out the currently 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()Code language: JavaScript (javascript)

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top