Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 655
Dmitrii Pisarenko Avatar asked Jul 01 '15 10:07

Dmitrii Pisarenko


People also ask

What is SecurityContextHolder getContext () getAuthentication ()?

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.

What is SecurityContextHolder in spring?

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.


1 Answers

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()
like image 190
Roman Vottner Avatar answered Oct 01 '22 23:10

Roman Vottner