.NetCore JwtBearerAuthentication 不拒绝过期令牌

.NetCore JwtBearerAuthentication not rejecting expired tokens(.NetCore JwtBearerAuthentication 不拒绝过期令牌)

本文介绍了.NetCore JwtBearerAuthentication 不拒绝过期令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am generating JWT's to use with my WebApi project. I'm set the token to expire in one minute so that I can test if it rejects the token when submitted after the expiration date.

创建令牌控制器

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
    });
}

令牌认证 - 启动类

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,但两分钟后令牌不会被拒绝.它将继续接受令牌.是否有我不知道的最短到期时间或我的设置有误?

Although I am setting validateLifetime = true the tokes are not rejected two minutes later. It will keep accepting the token. Is there a minimum expiration time that I am not aware of or is my setup wrong?

推荐答案

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

I stumbled over the answer here if anyone is interested. Default value for ClockSkew is 5 minutes.

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
    },
});

这篇关于.NetCore JwtBearerAuthentication 不拒绝过期令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:.NetCore JwtBearerAuthentication 不拒绝过期令牌

基础教程推荐