使用 Spring Security 时,在 bean 中获取当前用户名(即 SecurityContext)信息的正确方法是什么? [英] When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

查看:41
本文介绍了使用 Spring Security 时,在 bean 中获取当前用户名(即 SecurityContext)信息的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Spring Security 的 Spring MVC Web 应用程序.我想知道当前登录用户的用户名.我正在使用下面给出的代码片段.这是公认的方式吗?

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?

我不喜欢在这个控制器中调用静态方法——这违背了 Spring 的全部目的,恕我直言.有没有办法将应用程序配置为注入当前的 SecurityContext 或当前的身份验证?

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();
    ...
  }

推荐答案

如果您使用的是 Spring 3,最简单的方法是:

If you are using Spring 3, the easiest way is:

 @RequestMapping(method = RequestMethod.GET)   
 public ModelAndView showResults(final HttpServletRequest request, Principal principal) {

     final String currentUser = principal.getName();

 }

这篇关于使用 Spring Security 时,在 bean 中获取当前用户名(即 SecurityContext)信息的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆