.Net Core JwtBearer 身份验证不拒绝过期的令牌

.NetCore JwtBearerAuthentication not rejecting expired tokens

我正在生成 JWT 以用于我的 WebApi 项目。我将令牌设置为在一分钟后过期,以便我可以测试它是否在过期日期后拒绝提交令牌。

CreateToken控制器

public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
{
    var user = await _unitOfWork.UserManager.FindByNameAsync(model.UserName);

    if (user == null) return BadRequest();
    if (Hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) !=
        PasswordVerificationResult.Success) return BadRequest();

    var userClaims = await UserManager.GetClaimsAsync(user);

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), 
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email)
    }
    .Union(userClaims);

    var cert = new Certificate(Configuration["Tokens:Certificate"]);
    var token = new JwtSecurityToken(
        issuer: Configuration["Tokens:Issuer"],
        audience: Configuration["Tokens:Audience"],
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(1),
        signingCredentials: cert.Signature
    );

    return Ok(new
    {
        token = new JwtSecurityTokenHandler().WriteToken(token),
        expiration = token.ValidTo
    });
}

令牌验证 - 启动 Class

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = Configuration["Tokens:Issuer"],
        ValidAudience = Configuration["Tokens:Audience"],
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new Certificate(Configuration["Tokens:Certificate"]).SecurityKey,
        ValidateLifetime = true
    },
});

虽然我设置了 validateLifetime = true 两分钟后令牌没有被拒绝。它将继续接受令牌。是否有我不知道的最短到期时间,或者我的设置有误?

如果有人感兴趣的话,我偶然发现了答案 here。 ClockSkew 的默认值为 5 分钟。

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = Configuration["Tokens:Issuer"],
        ValidAudience = Configuration["Tokens:Audience"],
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new Certificate(certPath: Configuration["Tokens:Certificate"], isValid: false).SecurityKey,
        ValidateLifetime = true,
        ValidateIssuer = true,
        ValidateAudience = true,
        ClockSkew = TimeSpan.Zero
    },
});