问题
I have an API which uses ASP.NET Identity, it is fairly easy for me to get the UserId once the token
has been generated as following
HttpContext.Current.User.Identity.GetUserId().ToString())
Now I have an external application which is trying to authenticate using this API but I need the UserId of the user who generated the token
When I send a request to http://myapiURL/token
I get the following
- access_token
- token_type
- expires_in
- userName
- issued
- expires
And when I send a request to get API/Account/UserInfo
using the generated token
I get the following
- HasRegistered
- LoginProvider
Question How do I get UserId
?
I have two options,
A. I modify UserInfoViewModel GetUserInfo()
to have UserId in UserInfoViewModel?
B. I create a new method in ApiController
such as GetUserId (API/Account/GetUserId
) which runs HttpContext.Current.User.Identity.GetUserId().ToString())
and sends back the
UserId
Is there any other way?
Cheers
回答1:
I believe you want UserId in the response of /Token.
By default Identity does not add UserId in response.
so you need to add it manually in ApplicationOAuthProvider.cs in method 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);
}
来源:https://stackoverflow.com/questions/50461571/how-to-get-userid-from-asp-net-identity-when-sending-rest-request