使用 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章