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

I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I’m using the code snippet given below . Is this the accepted way?

I don’t like having a call to a static method inside this controller – that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?

  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView showResults(final HttpServletRequest request...) {
    final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
    ...
  }

17 Answers
17

Leave a Comment