spring security如何检索用户名 [英] spring security how to retrieve username

查看:121
本文介绍了spring security如何检索用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?

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

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;
    }
}

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

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);
    }


推荐答案

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

此外,可能是重复:使用Spring Security时,获取bean中当前用户名(即SecurityContext)信息的正确方法是什么?

这篇关于spring security如何检索用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆