从Web API OAuth承载身份验证中检索用户信息

Bru*_*ias 3 c# asp.net-mvc oauth-2.0 owin asp.net-web-api2

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

Request.GetOwinContext().Authentication.User.Identity.Name; // returns null
Run Code Online (Sandbox Code Playgroud)

我该如何实现?

Vic*_*ros 6

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

ControllerContext.RequestContext.Principal.Identity.Name;
Run Code Online (Sandbox Code Playgroud)

检查它是否已通过身份验证

ControllerContext.RequestContext.Principal.Identity.IsAuthenticated
Run Code Online (Sandbox Code Playgroud)

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

SimpleAuthorizationServerProvider:OAuthAuthorizationServerProvider

类)

 ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
Run Code Online (Sandbox Code Playgroud)

  • 就是这样!我不知道我们必须用声明填充name属性。谢谢! (2认同)