2011-05-28 65 views
57

我使用的是Spring Security 3和Spring MVC 3.05。从Spring MVC控制器的安全上下文获取UserDetails对象

我想打印当前登录用户的用户名,如何在我的控制器中获取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; 
    } 

回答

101

如果你已经知道了确保用户登录(在你的例子,如果/index.html保护):

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

如果要在用户登录第一次检查,检查当前的Authentication不是AnonymousAuthenticationToken

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

这给了我一个例外:'java.lang.ClassCastException:java.lang中.String不能转换成org.springframework.security.core.userdetails.UserDetails' – 2011-10-26 16:45:28

+1

给班级演员 – cherit 2011-11-18 05:28:44

+0

谢谢!非常感谢! – Lawrence 2014-09-30 13:47:00

3

如果你只是想在页面上打印用户名,也许你会喜欢这个解决方案。这是从对象铸件免费的,没有春季安全工作过:

@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方法来检索用户信息。

1

,如果你使用的是春天的安全,那么你可以得到登陆用户的电流

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
    String name = auth.getName(); //get logged in username 
23

让Spring 3注照顾这。

由于tsunade21最简单的方法是:

@RequestMapping(method = RequestMethod.GET) 
public ModelAndView anyMethodNameGoesHere(Principal principal) { 
     final String loggedInUserName = principal.getName(); 

} 
+0

令人惊叹。比在SecurityContextHolder中使用静态方法更容易进行测试。 – Planky 2016-07-15 20:41:35

1

这是另一种解决方案(春季安全3):

public String getLoggedUser() throws Exception { 
    String name = SecurityContextHolder.getContext().getAuthentication().getName(); 
    return (!name.equals("anonymousUser")) ? name : null; 
} 
相关问题