Spring Security如何检索用户名
可能的重复:
使用 Spring Security 时,在bean中获取当前用户名(即SecurityContext)信息的正确方法是什么?
我正在使用 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;
}
}
我在每个控制器方法中都获取此 Primary 对象。我不知道这是否是获得它的最佳方式。例如这里是代码
@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
ModelMap model, Principal principal) {
populateUserName(model, principal);
}
Possible Duplicate:
When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?
I am using spring security and i would like to know how to retrive the current logged in username in my controller. Can i store the userid associated to login username also somewhere?
Currently i am getting the username from Priciple object
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;
}
}
I am getting this Principal object in every controller method. I dont know if this is a optimal way to get it. For example here is the code
@RequestMapping(value = "/secure/myitem.htm", method = RequestMethod.GET)
public ModelAndView showItem(@RequestParam("listingId") String listingId,
ModelMap model, Principal principal) {
populateUserName(model, principal);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另外,可能是重复的:当使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?
Also, probably a duplicate: When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?
如果您需要的只是用户名,那么使用
Principal
是有意义的,因为您通过这种方式与 Spring Security API 隔离。您将需要调用某些内容来访问用户名,因此您不妨让 MVC 基础结构将其传递给您。如果您需要 Spring Security 的更多信息(而不仅仅是用户名),您可能需要查看此答案。您还可以在网上其他地方找到对此进行的讨论。
If all you need is the username, then using the
Principal
makes sense since you are isolated from Spring Security APIs that way. You will need to invoke something to access the username, so you might as well have the MVC infrastructure pass it to you.If you need more information from Spring Security (not just the username) you might want to look at this answer. You'll also find this discussed elsewhere online.