The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

1. Overview

This article will show how to retrieve the user details in Spring Security.

The current authenticated user is available through a number of different mechanisms in Spring – let’s cover the most common solution – programmatic access, first.

2. Get the User in a Bean

The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

An improvement to this snippet is first checking if there is an authenticate user before trying to access it:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUserName = authentication.getName();
    return currentUserName;
}

There are of course downsides to having a static call like this – decreased testability of the code being one of the more obvious. Instead, we will explore alternative solutions for this very common requirement.

3. Get the User in a Controller

In a @Controller annotated bean, there are additional options – the principal can be defined directly as a method argument and it will be correctly resolved by the framework:

import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

Alternatively, the authentication token can also be used:

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Authentication authentication) {
        return authentication.getName();
    }
}

The API of the Authentication class is very open so that the framework remains as flexible as possible. Because of this, the Spring Security principal can only be retrieved as an Object and needs to be casted to the correct UserDetails instance:

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());

And finally, directly from the HTTP request:

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }
}

4. Get the User via a Custom Interface

To fully leverage the Spring dependency injection and be able to retrieve the authentication everywhere, not just in @Controller beans, we need to hide the static access behind a simple facade:

public interface IAuthenticationFacade {
    Authentication getAuthentication();
}
@Component
public class AuthenticationFacade implements IAuthenticationFacade {

    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}

The facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable:

@Controller
public class SecurityController {
    @Autowired
    private IAuthenticationFacade authenticationFacade;

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple() {
        Authentication authentication = authenticationFacade.getAuthentication();
        return authentication.getName();
    }
}

5. Get the User in JSP

The currently authenticated principal can also be access in JSP pages, by leveraging the spring security taglib support. First, we need to define the tag in the page:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Next, we can refer to the principal:

<security:authorize access="isAuthenticated()">
    authenticated as <security:authentication property="principal.username" /> 
</security:authorize>

6. Conclusion

This article showed how to get the user information in a Spring application, starting with the common static access mechanism, followed with several better ways to inject the principal.

The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is. When the project runs locally, the homepage html can be accessed at:

http://localhost:8080/spring-security-rest-custom/foos/1

The Master Class "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

  • Jayakumar Jayaraman

    Hi Baeldung

    Thanks for the article.

    Can you please clarify the reverse of this…. i.e where to set the Authentication object after successfull login ?

    I have created a custom AuthenticationProvider. Should I add the authentication object in this class after successful login , as below ?

    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

    Thanks
    Jay

    • Glad you enjoyed the article.
      There is actually no direct reverse of this – Spring Security handles the process of storing the Authentication object, so in most cases, you won’t need to do that yourself. You can check out my article about implementing security for a REST service and also the Spring Security reference to better understand how to do this.
      Cheers,
      Eugen.

      • Jayakumar Jayaraman

        Sure thanks

  • Raj

    Hi,
    I am using Spring security active directory login. The Spring security by default is rendering a login page for me. Can you please give me some idea about how to log the user details in spring-security.xml

    • Hey Raj – you can create a listener for AuthenticationSuccessEvent where you have full access to the Authentication object. You can log it there. Cheers,
      Eugen.

  • josue Pech

    Hi,

    Thanks for the article, I just want to say that I liked a lot your idea of usign a Facade and it helps me a lot because I was look a way to wrap spring classes for testing.

    • Glad you found the concept useful Josue – I think it’s a quick but powerful abstraction – not to be over used, but definitely makes sense if a few key places. Cheers,
      Eugen.

  • Kurniawan

    hi,
    very good article, I am interested in trying how to get the user id of the user who logged in to perform queries on the other table.

    Thanks,

    • The internal user id doesn’t necessarily make it into your logged in principal, unless you specifically put it there. Simply put – when you implement your custom UserDetailsService (in case of course that’s what you’re using) – you’ll need to have a custom UserDetails implementation to represent your principal, and simply add the internal id of your user in there. Then, you can always have access to it at runtime.
      Hope that helps. Cheers,
      Eugen.

  • Hareesh Joshi

    Hi Eugen,

    Nice article. Can you please explain how to get an object of the type other than User from Authentication – stored as Principal? An example would be better.

    • Hey Hareesh – that’s an interesting question. The answer is that – the class that you’re able to get when you do getAuthentication().getPrincipal() depends on what class your Spring Security implementation is actually using as a Principal. So – you won’t be able to just retrieve or cast that to any implementation you need. You’ll have to – in your user details service implementation for instance – return the principal implementation you want. Then, on the other end – yes, you’ll be able to cast that to what you need.
      Hope that helps. Cheers,
      Eugen.

  • Jmp Jmp

    Great Info…

  • Michael Tabak

    In Craig Walls book “Spring Boot In Action”, he defines a custom UserDetails object by having a class Reader implement the UserDetails interface. Then in a controller, he accesses this Reader object by merely having it as a method parameter with no annotations and no form class binding via modellAttribue=”…” or commandName=”…” on the form page that triggers this method:

    @Controller
    @RequestMapping(“/”)
    public class BookController {

    @RequestMapping(method=RequestMethod.GET)
    public String readersBooks(Reader reader, Model model) {

    model.addAttribute(“reader”, reader);
    return “readingList”;
    }

    }

    Could you address why/how Spring knows to pass the populated Reader class into the method (assuming one has properly authenticated) in this case?

    • Have a look at the new(ish) @AuthenticationPrincipal annotation backed by AuthenticationPrincipalArgumentResolver – that should help with the direct injection of your custom principal. Cheers,
      Eugen.

      • Michael Tabak

        Yes, I am aware of @AuthenticationPrincipal. I just wasn’t aware of

        HandlerMethodArgumentResolver until I just discovered it. The code I was looking at was probably written just before
        @AuthenticationPrincipal was created.

        • Yeah, that may very well be the case – and so maybe they were using a custom resolver. Now that we have the annotation – that’s no longer needed.

  • Gustavo

    Hey Everybody. I have a doubt. Is there a way to know the users that are logged in? I’ve been looking for a kind of example but documentation says nothing about it. I know that you can get the user logged in through springSecurityService, but if you have users list, I’ll be fine to know which users are logged in.