本文介绍了从Spring MVC控制器中的Security Context获取UserDetails对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Spring Security 3和Spring MVC 3.05。
I'm using Spring Security 3 and Spring MVC 3.05.
我想打印当前登录用户的用户名,如何在Controller中获取UserDetails ?
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();
要首先检查用户是否已登录,请检查当前身份验证
不是 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控制器中的Security Context获取UserDetails对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!