Get UserDetails Object from Security Context in Spring MVC Controller

I am using Spring Security 3 and Spring MVC 3.05.

I would like to print the username of the current user, how can I get 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; } 
+55
java spring spring-mvc spring-security
May 28 '11 at 13:41
source share
5 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 check if a user is logged in first, make sure that the current Authentication not AnonymousAuthenticationToken .

 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { // userDetails = auth.getPrincipal() } 
+96
May 28 '11 at 14:04
source share

Let Spring 3 injection take care of this.

Thanks to tsunade21 the easiest way:

  @RequestMapping(method = RequestMethod.GET) public ModelAndView anyMethodNameGoesHere(Principal principal) { final String loggedInUserName = principal.getName(); } 
+23
Apr 02 '14 at 19:43
source share

If you just want to print the username on the pages, you might like this solution. It is free from object casting 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. Added parameter HttpServletRequest request .

This works fine because Spring introduces its own objects (wrappers) for HttpServletRequest, Principal, etc., so you can use standard java methods to retrieve user information.

+3
Jul 25 2018-12-12T00:
source share

if you use spring protection then you can get the current logged in user

 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); //get logged in username 
+1
Feb 08 '13 at 11:13
source share

This is another solution (Spring Security 3):

 public String getLoggedUser() throws Exception { String name = SecurityContextHolder.getContext().getAuthentication().getName(); return (!name.equals("anonymousUser")) ? name : null; } 
0
Aug 13 '15 at 10:16
source share



All Articles