- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我目前在 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/
在 token 验证中,我检查了 token 的生命周期,它是13:07:10。当我运行验证时,时间是 13:12,验证成功。 为什么? 当大约是 13:15 时,我再次运行验证,结果如预期的那样抛出
我需要检查我的 JwtSecurityToken 是否过期。 我正在使用 System.IdentityModel.Tokens.Jwt 库。 当我像这样创建一个 JwtSecurityToken 时
我目前在 System.IdentityModels.Tokens 命名空间中使用 JwtSecurityToken 类。我使用以下方法创建 token : DateTime expires = Da
我对 JwtSecurityTokens 还很陌生,我试着去了解它的不同方面,甚至是整个 claimsidentity和 claimprincipal ,但那是另一回事了。 我尝试在 中生成 toke
我正在实现 mechanizm 来管理我的应用程序中的 token ,并且我使用这样的代码来创建 JwtSecurityToken var securityTokenDescriptor = new
我有两个库。一个消耗另一个,消耗库本身由 Web 应用程序使用。 Web 应用程序返回以下错误,而实例化类型的代码(掺杂 JWT 签名验证)在两个库的单元测试中成功执行。库、应用程序是目标框架 .NE
我的 AuthServer 当前正在使用以下代码生成 JwtSecurityToken: var token = new JwtSecurityToken(_issuer, audienceId, d
以下代码: using System.IdentityModel.Tokens; JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(ra
我是一名优秀的程序员,十分优秀!