从 Spring MVC 控制器中的安全上下文获取 UserDetails 对象 [英] Get UserDetails object from Security Context in Spring MVC controller

查看:47
本文介绍了从 Spring MVC 控制器中的安全上下文获取 UserDetails 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Spring Security 3 和 Spring MVC 3.05.

I'm using Spring Security 3 and Spring MVC 3.05.

我想打印当前登录用户的用户名,如何在我的控制器中获取用户详细信息?

I would like to print username of currently logged in user,how can I fetch UserDetails in my Controller?

@RequestMapping(value="/index.html", method=RequestMethod.GET)
    public ModelAndView indexView(){
         UserDetails user = ?
                mv.addObject("username", user.getUsername());
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }   

推荐答案

如果您已经确定用户已登录(在您的示例中,如果 /index.html 受到保护):

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

首先检查用户是否登录,检查当前的Authentication是否不是AnonymousAuthenticationToken.

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

这篇关于从 Spring MVC 控制器中的安全上下文获取 UserDetails 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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