【问题标题】:How to get Identity User from his authentication JWT token in .Net Core API?如何从.Net Core API 中的身份验证 JWT 令牌中获取身份用户?
【发布时间】:2020-06-12 03:49:51
【问题描述】:

我使用 .Net Core 作为我的 API,所以没有意见或任何意见。我还使用 ASP.net Core Identity 框架来授权我的数据库中的用户。 对于登录用户,我使用以下代码:

private string GenerateAuthenticationResult(ApplicationUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                // Things to be included and encoded in the token
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim("id", user.Id)
                }),
                // Token will expire 2 hours from which it was created
                Expires = DateTime.UtcNow.AddHours(2),
                //
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);
        }

这就像验证用户操作的魅力,但如果用户使用我之前提供的令牌登录他的请求标头(Bearer),我怎么知道我的服务器正在与谁交谈。

TL;博士

我想从请求标头中提供的令牌中提取用户 ID 或用户电子邮件。

谢谢。

【问题讨论】:

    标签: rest api asp.net-core .net-core jwt


    【解决方案1】:

    您可以使用AddJwtBearer 验证 JWT 令牌:

    var sharedKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("yourkey"));
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
    
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = sharedKey,
    
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = false,            
        };
    });
    

    并通过在Configure方法中添加app.UseAuthentication();来启用asp.net核心认证中间件。之后,您可以在受保护的操作/控制器上添加[Authorize] 属性。

    在验证后获取电子邮件和用户 ID:

    var  email= User.Claims.Where(x => x.Type == ClaimTypes.Email).FirstOrDefault()?.Value;
    var  userid= User.Claims.Where(x => x.Type == "id").FirstOrDefault()?.Value;
    

    这里使用ClaimTypes.Email,因为JwtRegisteredClaimNames.Email会被中间件自动映射到ClaimTypes.Email。见source code

    以下是一些关于 JWT 身份验证的有用文章:

    https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

    https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api

    【讨论】:

    • 你救了我的命。非常感谢。
    猜你喜欢
    • 2021-12-17
    • 2019-06-17
    • 2019-02-22
    • 2020-02-05
    • 2020-10-25
    • 2020-10-15
    • 2019-01-22
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多