java上下文获取登录用户,java-从Spring MVC con中的安全上下文获取UserDetails对象
java-从Spring MVC con中的安全上下文获取UserDetails对象我正在使用Spring Security 3和Spring MVC 3.05。我想打印当前登录用户的用户名,如何在Controller中获取UserDetails?@RequestMapping(value="/index.html", method=RequestMethod.GET)public ModelAn
java-从Spring MVC con中的安全上下文获取UserDetails对象
我正在使用Spring Security 3和Spring MVC 3.05。
我想打印当前登录用户的用户名,如何在Controller中获取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;
}
5个解决方案
111 votes
如果您已经确定用户已经登录(在您的示例中,如果Authentication受保护),请执行以下操作:
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
要首先检查用户是否已登录,请检查当前的Authentication不是AnonymousAuthenticationToken。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// userDetails = auth.getPrincipal()
}
sourcedelica answered 2019-10-04T05:08:41Z
31 votes
让Spring 3注入处理此问题。
感谢tsunade21,最简单的方法是:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView anyMethodNameGoesHere(Principal principal) {
final String loggedInUserName = principal.getName();
}
Farm answered 2019-10-04T05:09:12Z
4 votes
如果您只想在页面上打印用户名,也许您会喜欢这种解决方案。 它没有对象转换,也可以在没有Spring Security的情况下工作:
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("index");
String userName = "not logged in"; // Any default user name
Principal principal = request.getUserPrincipal();
if (principal != null) {
userName = principal.getName();
}
mv.addObject("username", userName);
// By adding a little code (same way) you can check if user has any
// roles you need, for example:
boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
mv.addObject("isAdmin", fAdmin);
return mv;
}
注意添加了“ HttpServletRequest请求”参数。
之所以能正常工作,是因为Spring为HttpServletRequest,Principal等注入了自己的对象(包装器),因此您可以使用标准的Java方法来检索用户信息。
L'sync answered 2019-10-04T05:09:52Z
1 votes
那是另一种解决方案(Spring Security 3):
public String getLoggedUser() throws Exception {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return (!name.equals("anonymousUser")) ? name : null;
}
Alexey Nikitenko answered 2019-10-04T05:10:17Z
1 votes
如果您使用的是Spring Security,则可以通过获取当前登录用户
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
amit answered 2019-10-04T05:10:42Z
更多推荐




所有评论(0)