Asp.net Identity 2 User.Identity.GetUserId <int>()总是返回0?

时间:2015-07-29 15:39:50

标签: asp.net-identity-2

通过关注thisthis之类的帖子,我扩展了Asp.net Identity 2模型以使用整数键。但是,这行代码始终返回0.

User.Identity.GetUserId<int>()

即使User.Identity.IsAuthenticated为true且User.Identity.GetUserName()返回正确的用户名。我见过this post但它没有用,因为我已经在控制器方法中调用了User.Identity.GetUserId()而不是构造函数。该帖子中对“getUserIdCallback”的引用虽然很有趣,但也许我需要这样的东西。任何帮助深表感谢。

1 个答案:

答案 0 :(得分:7)

事实证明,我需要在自定义OAuthAuthorizationServerProvider的GrantResourceOwnerCredentials方法中将用户的ID添加到ClaimsIdentity。这是方法:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*";

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

    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;
    }

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    //THIS IS THE IMPORTANT LINE HERE!!!!!
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    identity.AddClaim(new Claim("sub", context.UserName));

    foreach (var role in userManager.GetRoles(user.Id))
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, role));
    }

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        { "as:client_id", context.ClientId ?? string.Empty }
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}