How to get UserID from ASP.NET Identity when sending Rest Request

允我心安 提交于 2021-02-10 14:16:26

问题


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

  1. access_token
  2. token_type
  3. expires_in
  4. userName
  5. issued
  6. expires

And when I send a request to get API/Account/UserInfo using the generated token I get the following

  1. Email
  2. HasRegistered
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!