【问题标题】:How to get UserID from ASP.NET Identity when sending Rest Request发送 Rest Request 时如何从 ASP.NET Identity 获取 UserID
【发布时间】:2018-10-31 20:40:20
【问题描述】:

我有一个使用 ASP.NET 标识的 API,一旦生成了如下的 token,我就很容易获得 UserId

HttpContext.Current.User.Identity.GetUserId().ToString())

现在我有一个外部应用程序正在尝试使用此 API 进行身份验证,但我需要生成 token 的用户的 UserId

当我向http://myapiURL/token 发送请求时,我得到以下信息

  1. access_token
  2. token_type
  3. expires_in
  4. 用户名
  5. 发布
  6. 过期

当我使用生成的token 发送获取API/Account/UserInfo 的请求时,我得到以下信息

  1. 电子邮件
  2. 已注册
  3. 登录提供者

问题我如何获得UserId

我有两个选择,

A. 我将UserInfoViewModel GetUserInfo() 修改为在UserInfoViewModel 中有UserId?

B. 我在 ApiController 中创建了一个新方法,例如运行 HttpContext.Current.User.Identity.GetUserId().ToString()) 的 GetUserId (API/Account/GetUserId) 并发送回 用户ID

还有其他方法吗?

干杯

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    我相信您希望 UserId 在 /Token 的响应中。

    默认情况下,Identity 不会在响应中添加 UserId。

    所以您需要在 ApplicationOAuthProvider.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);
            }
    

    【讨论】:

    • 这是个好主意,感谢您,使用 ticket.Properties.Dictionary.Add("UserId", user.Id); 也只需返回 UserId - 完美解决方案
    猜你喜欢
    • 2013-10-30
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多