In this Spring Boot application there is a web service, which returns some data for a logged-in user:
@RequestMapping("/resource") public Map<String, Object> home() { Map<String, Object> model = new HashMap<String, Object>(); model.put("id", UUID.randomUUID().toString()); model.put("content", "Hello World"); return model; }
Imagine, the return value of the method depends on what user is currently logged in.
How can I find out, which user is logged in in that method?
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
The SecurityContextHolder is a helper class, which provide access to the security context. By default, it uses a ThreadLocal object to store security context, which means that the security context is always available to methods in the same thread of execution, even if you don't pass the SecurityContext object around.
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:
getPrincipal()
getCredentials()
getAuthorities()
getDetails()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With