spring security如何检索用户名

时间:2012-02-16 18:59:44

标签: java spring spring-mvc spring-security

  

可能重复:
  When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

我正在使用spring security,我想知道如何在我的控制器中检索当前登录的用户名。我可以在某处存储与登录用户名相关联的用户ID吗? 目前我从Priciple对象

获取用户名
public boolean populateUserName(ModelMap model, Principal principal) {
    if (principal != null) {
        String name = principal.getName();
        model.addAttribute("username", name);
        System.out.println("userName - " + name);
        return true;
    }
    else
    {
        System.out.println("principal is null");
        return false;
    }
}

我在每个控制器方法中获取此Principal对象。我不知道这是否是获得它的最佳方式。例如,这里是代码

@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
        ModelMap model, Principal principal) {
    populateUserName(model, principal);
    }

2 个答案:

答案 0 :(得分:6)

SecurityContextHolder.getContext().getAuthentication().getName()

另外,可能是重复:When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

答案 1 :(得分:1)

如果你需要的只是用户名,那么使用Principal是有道理的,因为你是这样与Spring Security API隔离的。您将需要调用某些内容来访问用户名,因此您可以将MVC基础结构传递给您。

如果您需要Spring Security提供的更多信息(而不仅仅是用户名),您可能需要查看this answer。你也会在网上其他地方找到这个。