【问题标题】:User.Identity.GetUserId() and RequestContext.Principal.Identity.GetUserId() returns NULL in WEB API controller. Used Token based AunthenticationUser.Identity.GetUserId() 和 RequestContext.Principal.Identity.GetUserId() 在 WEB API 控制器中返回 NULL。使用基于令牌的身份验证
【发布时间】:2016-07-11 05:09:20
【问题描述】:

我使用令牌来保护我的 Web API 网站,并从 AngularJS 客户端应用程序中使用此 API。

有了这个,我可以使用基于令牌的身份验证登录。我的问题是我无法在 Web API 控制器中获取 UserId

User.Identity.GetUserId()RequestContext.Principal.Identity.GetUserId() 都返回 null

如何在ApiController 中获取UserId

【问题讨论】:

  • 你用的是什么框架? ASP.NET 身份?
  • 是的。身份 2.0 ,MVC 5. WEB API
  • User.Identity.GetUserId() 应该返回当前登录用户的用户 ID。您是否在调用 WebAPI 时尝试在 Authorization 标头中使用登录用户(传递 Bearer AuthToken)?
  • 已解决.. 将 AuthToken 作为标头传递时出现问题。现在它工作正常.. 谢谢....
  • @RohitV 请解释一下或分享代码 sn-ps 你如何解决你的问题我遇到同样的问题谢谢!

标签: angularjs asp.net-web-api http-token-authentication


【解决方案1】:

如果您已经拥有不记名令牌,请在 javascript 中设置 Authorization 标头。

var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
    headers.Authorization = 'Bearer ' + token;
}

那么您应该在您的 ajax 请求中包含标头:

 $.ajax({
        type: 'GET',
        url: 'api/values/1',
        headers: headers
    }).done(function (data) {
        self.result(data);
    }).fail(showError);

最后在你的控制器中,你可以通过以下方式获取用户 ID:

var userId = RequestContext.Principal.Identity.GetUserId();

更多信息请参考Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2016-07-31
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多