如何从.Net Core API中的身份验证JWT令牌中获取身份用户?

时间:2020-02-28 03:48:15

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

我将 .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);
        }

这就像用于验证用户操作的超级按钮一样,但是如果用户使用我之前提供的令牌登录他的请求标头(承载者),那么我如何知道服务器正在与谁进行通讯。

TL;博士

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

谢谢。

1 个答案:

答案 0 :(得分: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,            
    };
});

并通过在app.UseAuthentication();方法中添加Configure来启用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