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; }
The getPrincipal() method normally return UserDetails object in Spring Security, which contains all the details of currently logged in user.
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.
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() }
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