gpt4 book ai didi

c# - .Net Core JwtBearer 身份验证不拒绝过期的 token

转载 作者:可可西里 更新时间:2023-11-01 08:22:22 27 4
gpt4 key购买 nike

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

CreateToken Controller

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

token 认证 - 启动类

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,但两分钟后 token 并没有被拒绝。它将继续接受 token 。是否存在我不知道的最短到期时间或者我的设置有误?

最佳答案

我偶然发现了答案 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
},
});

关于c# - .Net Core JwtBearer 身份验证不拒绝过期的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com