Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UserDetails object from Security Context in Spring MVC controller

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;     }    
like image 407
danny.lesnik Avatar asked May 28 '11 13:05

danny.lesnik


People also ask

Which method normally returns UserDetails object in Spring Security?

The getPrincipal() method normally return UserDetails object in Spring Security, which contains all the details of currently logged in user.

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.


1 Answers

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() } 
like image 70
sourcedelica Avatar answered Sep 21 '22 02:09

sourcedelica