gpt4 book ai didi

c# - JwtSecurityToken 不会在应该过期的时候过期

转载 作者:IT王子 更新时间:2023-10-29 04:29:16 27 4
gpt4 key购买 nike

我目前在 System.IdentityModels.Tokens 命名空间中使用 JwtSecurityToken 类。我使用以下方法创建 token :

DateTime expires = DateTime.UtcNow.AddSeconds(10);
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
var genericIdentity = new System.Security.Principal.GenericIdentity(username, "TokenAuth");

ClaimsIdentity identity = new ClaimsIdentity(claims);
string secret = ConfigurationManager.AppSettings["jwtSecret"].ToString();
var securityKey = new InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret));
var signingCreds = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.HmacSha256Signature);
var securityToken = handler.CreateToken(
issuer: issuer,
audience: ConfigurationManager.AppSettings["UiUrl"].ToString(),
signingCredentials: signingCreds,
subject: identity,
expires: expires,
notBefore: DateTime.UtcNow
);
return handler.WriteToken(securityToken);

出于某种原因,即使过期时间设置为当前时间后 10 秒,但在验证 token 时直到大约 5 分钟时它才真正抛出异常。看到这里,我想可能有一个最短的5分钟过期时间,所以我将过期时间设置为:

DateTime.UtcNow.AddMinutes(5);

然后它在 10 分钟后过期,但是异常消息说过期时间设置为它应该的时间(用户登录后 5 分钟),当它在异常中显示当前时间时它是到期时间后 5 分钟。所以,它似乎知道它什么时候应该过期,但直到过期时间 5 分钟后它才真正抛出异常。然后,由于 token 似乎在我将其设置为过期的任何时间后增加 5 分钟,因此我将过期时间设置为:

DateTime.UtcNow.AddMinutes(-5).AddSecond(10);

我测试了这个,到目前为止它还没有过期(十多分钟后)。有人可以解释为什么会这样以及我做错了什么吗?此外,如果您在我提供的代码中看到任何其他内容,我们将不胜感激,因为我是使用 JWT 和此库的新手。

最佳答案

问题与 ClockSkew 有关。通常,验证库(至少是 MS 库)会补偿时钟偏差。 ClockSkew 默认值为 5 分钟。查看一些答案 here

您可以在 TokenValidationParameters 中更改 ClockSkew:

var tokenValidationParameters = new TokenValidationParameters
{
//...your setting

// set ClockSkew is zero
ClockSkew = TimeSpan.Zero
};

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});

编码愉快!

关于c# - JwtSecurityToken 不会在应该过期的时候过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728519/

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