Reputation: 2768
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
And when I send a request to get API/Account/UserInfo
using the generated token
I get the following
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
Upvotes: 1
Views: 1716
Reputation: 5962
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);
}
Upvotes: 1