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

As per request:

Spring Boot which uses Spring Security internally provides a SecurityContextHolder class which allows the lookup of the currently authenticated user via:

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()

Leave a Comment