我有一个使用 ASP.NET 身份的API,一旦生成token
,我就很容易获得UserId,如下所示
HttpContext.Current.User.Identity.GetUserId().ToString())
现在我有一个外部应用程序,它正在尝试使用此 API 进行身份验证,但我需要生成token
的用户的 UserId
当我向http://myapiURL/token
发送请求时,我收到以下内容
- access_token
- token_type
- expires_in
- 用户名
- 发出
- 到期
当我使用生成的token
发送请求以获取API/Account/UserInfo
时,我得到以下内容
- 电子邮件
- 已注册
- 登录提供程序
问题我如何获得UserId
?
我有两个选择,
A.我修改UserInfoViewModel GetUserInfo()
以在UserInfoViewModel中使用UserId?
B.我在ApiController
中创建一个新方法,例如 GetUserId (API/Account/GetUserId
(,它运行HttpContext.Current.User.Identity.GetUserId().ToString())
并发回 用户标识
还有其他办法吗?
干杯
我相信您希望 UserId 出现在/Token 的响应中。
默认情况下,标识不会在响应中添加用户 ID。
所以你需要在应用程序OAuth提供程序中手动添加它.cs在方法GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
ticket.Properties.Dictionary.Add("UserId", user.Id);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}