Search code examples
javaspring-boot

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?


Solution

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