【问题标题】:Asp.net Identity 2 User.Identity.GetUserId<int>() always returns 0?Asp.net Identity 2 User.Identity.GetUserId<int>() 总是返回 0?
【发布时间】:2015-07-29 15:39:49
【问题描述】:

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

User.Identity.GetUserId<int>()

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

【问题讨论】:

    标签: asp.net-identity-2


    【解决方案1】:

    事实证明,我需要在自定义 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);
    }
    

    【讨论】:

    • 谢谢,这对我很有用
    猜你喜欢
    • 2019-04-15
    • 2016-05-12
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多