0

Possible Duplicate:
When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

I am using spring security and i would like to know how to retrive the current logged in username in my controller. Can i store the userid associated to login username also somewhere? Currently i am getting the username from Priciple object

public boolean populateUserName(ModelMap model, Principal principal) {
    if (principal != null) {
        String name = principal.getName();
        model.addAttribute("username", name);
        System.out.println("userName - " + name);
        return true;
    }
    else
    {
        System.out.println("principal is null");
        return false;
    }
}

I am getting this Principal object in every controller method. I dont know if this is a optimal way to get it. For example here is the code

@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
        ModelMap model, Principal principal) {
    populateUserName(model, principal);
    }
Community
  • 1
  • 1
Abdus Samad
  • 343
  • 2
  • 12
  • 27

2 Answers2

6
SecurityContextHolder.getContext().getAuthentication().getName()

Also, probably a duplicate: When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

If all you need is the username, then using the Principal makes sense since you are isolated from Spring Security APIs that way. You will need to invoke something to access the username, so you might as well have the MVC infrastructure pass it to you.

If you need more information from Spring Security (not just the username) you might want to look at this answer. You'll also find this discussed elsewhere online.

Community
  • 1
  • 1
Shaun the Sheep
  • 22,353
  • 1
  • 72
  • 100