Get UserDetails object from Security Context in Spring MVC controller

JavaSpringSpring MvcSpring Security

Java Problem Overview


I'm using Spring Security 3 and Spring MVC 3.05.

I would like to print username of currently logged in user,how can I fetch UserDetails in my Controller?

@RequestMapping(value="/index.html", method=RequestMethod.GET)
	public ModelAndView indexView(){
         UserDetails user = ?
                mv.addObject("username", user.getUsername());
		ModelAndView mv = new ModelAndView("index");
		return mv;
	}	

Java Solutions


Solution 1 - Java

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

Solution 2 - Java

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }

Solution 3 - Java

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

	ModelAndView mv = new ModelAndView("index");

	String userName = "not logged in"; // Any default user  name
	Principal principal = request.getUserPrincipal();
	if (principal != null) {
		userName = principal.getName();
	}

	mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

	return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

Solution 4 - Java

if you are using spring security then you can get the current logged in user by

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String name = auth.getName(); //get logged in username

Solution 5 - Java

That's another solution (Spring Security 3):

public String getLoggedUser() throws Exception {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return (!name.equals("anonymousUser")) ? name : null;
}

Solution 6 - Java

You can use below code to find out principal (user email who logged in)

  org.opensaml.saml2.core.impl.NameIDImpl principal =  
  (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

  String email = principal.getValue();

This code is written on top of SAML.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondanny.lesnikView Question on Stackoverflow
Solution 1 - JavasourcedelicaView Answer on Stackoverflow
Solution 2 - JavaFarmView Answer on Stackoverflow
Solution 3 - JavaL'syncView Answer on Stackoverflow
Solution 4 - JavaamitView Answer on Stackoverflow
Solution 5 - JavaAlexey NikitenkoView Answer on Stackoverflow
Solution 6 - JavaShekhar KadamView Answer on Stackoverflow