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)

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.