【问题标题】:Retrieve user information from Web API OAuth Bearer authentication从 Web API OAuth Bearer 身份验证中检索用户信息
【发布时间】:2018-02-28 20:05:20
【问题描述】:

我有一个使用令牌验证的有效 Web API,但我想检索发送该令牌的用户。

Request.GetOwinContext().Authentication.User.Identity.Name; // returns null

我怎样才能做到这一点?

【问题讨论】:

    标签: c# asp.net-mvc oauth-2.0 asp.net-web-api2 owin


    【解决方案1】:

    我使用 owin 并以这种方式获取当前用户

    ControllerContext.RequestContext.Principal.Identity.Name;
    

    检查是否已通过身份验证

    ControllerContext.RequestContext.Principal.Identity.IsAuthenticated
    

    确保用户名以这种方式链接到令牌(它在我的

    SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider

    类)

     ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    

    【讨论】:

    • ControllerContext.RequestContext.Principal.Identity.Name;正在返回 null,即使 IsAuthenticated 为真。你知道我可能会错过什么吗?谢谢!
    • 您确定将用户名添加到声明中吗?我编辑了答案
    • 就是这样!我不知道我们必须用声明填充名称属性。谢谢!
    猜你喜欢
    • 2014-05-02
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多