ASP.NET Core JWT身份验证允许过期的令牌。

12

由于某些原因,我的RESTful应用程序在一段时间内允许来自Angular客户端的已过期令牌请求。生成令牌:

private async Task<string> GenerateJwtToken(ApplicationUser user)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id)
    };
    claims.AddRange(await _userManager.GetClaimsAsync(user));
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("SigningKey").Value));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var expires = 
        DateTime.Now.AddSeconds(10);
        //DateTime.Now.AddDays(Convert.ToDouble(_configuration["ExpireDays"]));

    var token = new JwtSecurityToken(
        issuer: _configuration["Issuer"],
        audience: _configuration["Audience"],
        claims: claims,
        expires: expires,
        signingCredentials: creds);
    return new JwtSecurityTokenHandler().WriteToken(token);
}

在请求之前,我记录了过期时间、当前时间以及当前时间是否超过了过期时间。记录了两次成功的请求日志,但最后一次应该失败。

t: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time) credentials-service.ts:101

now: Tue Sep 18 2018 08:53:41 GMT+0300 (Moscow Standard Time) credentials-service.ts:102

false

true表示已经过期

credentials-service.ts:100 t: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time)

credentials-service.ts:101 now: Tue Sep 18 2018 08:58:01 GMT+0300 (Moscow Standard Time)

credentials-service.ts:102

true

由于某种原因,我在5-6分钟后才被拒绝,而不是10秒钟。

1
在令牌验证设置中找到ClockSkew设置;通常允许一点时间来解决服务器时钟不同步的问题。 - juunas
1
你应该像这里所示的例子一样使用ClockSkew - https://dev59.com/maXja4cB1Zd3GeqPLAhm - Алексей Сидоров
1个回答

30

在Startup.cs中定义TokenValidationParameters时,将ClockSkew属性设置为零的TimeSpan值:

ClockSkew = TimeSpan.Zero, 例如:

new TokenValidationParameters
                {
                    IssuerSigningKey = signingKey,
                    ValidIssuer = issuer,
                    ValidAudience = audience,
                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                };

这是因为ClockSkew有一个默认值为5分钟。


2
我的英雄! - ViqMontana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接