为了账号安全,请及时绑定邮箱和手机立即绑定

使用Spring Security时,获取bean中当前用户名(即SecurityContext)

使用Spring Security时,获取bean中当前用户名(即SecurityContext)

30秒到达战场 2019-08-23 15:46:45
使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?我有一个使用Spring Security的Spring MVC Web应用程序。我想知道当前登录用户的用户名。我正在使用下面给出的代码段。这是接受的方式吗?我不喜欢在这个控制器中调用静态方法 - 这违背了Spring的全部目的,恕我直言。有没有办法配置应用程序以注入当前的SecurityContext或当前的身份验证?  @RequestMapping(method = RequestMethod.GET)   public ModelAndView showResults(final HttpServletRequest request...) {     final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();     ...   }
查看完整描述

3 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

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

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

     final String currentUser = principal.getName();

 }


查看完整回答
反对 回复 2019-08-23
?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

如果您使用的是Spring Security ver> = 3.2,则可以使用@AuthenticationPrincipal注释:

@RequestMapping(method = RequestMethod.GET)public ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {
    String currentUsername = currentUser.getUsername();
    // ...}

CustomUser是一个自定义对象,它实现UserDetails了自定义返回的对象UserDetailsService

可以在Spring Security参考文档的@AuthenticationPrincipal章节中找到更多信息。


查看完整回答
反对 回复 2019-08-23
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

Principal在控制器方法中定义为依赖项,spring将在调用时在方法中注入当前经过身份验证的用户。


查看完整回答
反对 回复 2019-08-23
  • 3 回答
  • 0 关注
  • 3035 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信