使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么? [英] When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?
问题描述
我有一个使用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屋!