.NetCore JwtBearerAuthentication不拒绝过期的令牌

Dbl*_*247 14 c# jwt asp.net-core asp.net-core-identity

我正在生成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
    });
}
Run Code Online (Sandbox Code Playgroud)

令牌认证 - 启动类

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
    },
});
Run Code Online (Sandbox Code Playgroud)

虽然我设置了validateLifetime = true,但两分钟之后不会拒绝tokes.它将继续接受令牌.是否存在我不知道的最短到期时间或我的设置错误?

Dbl*_*247 17

如果有人有兴趣,我在这里偶然发现了答案.

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
    },
});
Run Code Online (Sandbox Code Playgroud)

  • 小心将clockkew设置为Zero.您可能会遇到一些客户的问题. (3认同)
  • 你总是可以做 `ClockSkew = Debugger.IsAttached 吗?TimeSpan.Zero : TimeSpan.FromMinutes(10)` 所以在调试期间你不需要处理它 - 假设你正在使用自己的机器或你知道时间正确的机器。但是如果你忘记把它改回来,你以后就不会遇到麻烦了。 (2认同)