使用 Spring Security 时,在 bean 中获取当前用户名(即 SecurityContext)信息的正确方法是什么?

问题:

I have a Spring MVC web app which uses Spring Security.我有一个使用 Spring Security 的 Spring MVC Web 应用程序。 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.我不喜欢在这个控制器中调用静态方法 - 这违背了 Spring 的全部目的,恕我直言。 Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?有没有办法将应用程序配置为注入当前的 SecurityContext 或当前的身份验证?

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

解决方案:

参考一: https://en.stackoom.com/question/12f4
参考二: https://stackoom.com/question/12f4
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章