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:
- Get the password of the authenticated user:
- Get the assigned roles of the authenticated user:
- Get further details of the authenticated user:
Example to get logged-in user using SecurityContextHolder class
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Get user name authentication.getName()
Kuzu Zangpo la! I am Sonam Dargay. I am a full-time software developer. Apart from 9-5 office works, I am a tech enthusiast, blogger, and dreamer.
I graduated from the College of Science and Technology(CST), affiliated with the Royal University of Bhutan.