【发布时间】:2017-02-05 07:30:55
【问题描述】:
我目前在 System.IdentityModels.Tokens 命名空间中使用 JwtSecurityToken 类。我使用以下内容创建了一个令牌:
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);
由于某种原因,即使将 expires 设置为当前时间之后的 10 秒,在验证令牌时它实际上不会引发异常,直到大约 5 分钟。看到这里,我想可能是最小过期时间为 5 分钟,所以我将过期时间设置为:
DateTime.UtcNow.AddMinutes(5);
然后它在 10 分钟过期,但异常消息说过期时间设置为应有的时间(用户登录后 5 分钟),当它在异常中显示当前时间时它是过期时间后 5 分钟。因此,它似乎知道它应该何时过期,但实际上直到过期时间后 5 分钟才抛出异常。然后,由于令牌似乎在我将其设置为过期的任何时间上增加了 5 分钟,因此我将过期时间设置为:
DateTime.UtcNow.AddMinutes(-5).AddSecond(10);
我对此进行了测试,到目前为止它还没有过期(十多分钟后)。有人可以解释为什么会发生这种情况以及我做错了什么吗?此外,如果您在我提供的代码中看到任何其他内容,我们将不胜感激,因为我是使用 JWT 和这个库的新手。
【问题讨论】: