我使用的是Spring Security 3和Spring MVC 3.05。
我想打印当前登录用户的用户名,如何在控制器中获取UserDetails?
@RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView indexView(){
UserDetails user = ?
mv.addObject("username", user.getUsername());
ModelAndView mv = new ModelAndView("index");
return mv;
}
发布于 2011-05-28 22:04:17
如果您已经确定用户已登录(在您的示例中,如果/index.html
是受保护的):
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
要首先检查用户是否已登录,请检查当前Authentication
是否不是AnonymousAuthenticationToken
。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// userDetails = auth.getPrincipal()
}
发布于 2014-04-03 03:43:23
让Spring3注入来解决这个问题。
多亏了tsunade21,最简单的方法是:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView anyMethodNameGoesHere(Principal principal) {
final String loggedInUserName = principal.getName();
}
发布于 2013-02-08 19:13:02
如果您使用的是spring security,则可以通过以下方式获取当前登录的用户
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
https://stackoverflow.com/questions/6161985
复制相似问题