問題描述
我目前在 System.IdentityModels.Tokens 命名空間中使用 JwtSecurityToken 類.我使用以下內容創建了一個令牌:
I am currently using the JwtSecurityToken class in System.IdentityModels.Tokens namespace. I create a token using the following:
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 分鐘,所以我將過期時間設置為:
For some reason even though the expires is set to 10 seconds after the current time it doesn't actually throw an exception when the token is being validated until about 5 minutes. After seeing this, I thought maybe there was a minimum expire time of 5 minutes, so I set the expire time to:
DateTime.UtcNow.AddMinutes(5);
然后它在 10 分鐘過期,但是異常消息說過期時間設置為應有的時間(用戶登錄后 5 分鐘),當它在異常中顯示當前時間時它是過期時間后 5 分鐘.因此,它似乎知道它應該何時過期,但實際上直到過期時間后 5 分鐘才拋出異常.然后,由于令牌似乎在我將其設置為過期的任何時間上增加了 5 分鐘,因此我將過期時間設置為:
Then it expires at 10 minutes, but the exception message says that the expire time is set to what it is supposed to be (5 minutes after the user logs in), and when it shows the current time in the exception it is 5 minutes after the expire time. So, it seems to know when it SHOULD expire, but it doesn't actually throw the exception until 5 minutes after the expire time. Then, since the token seems to be adding 5 minutes to whatever time I set it to expire I set the expire time to:
DateTime.UtcNow.AddMinutes(-5).AddSecond(10);
我對此進行了測試,到目前為止它還沒有過期(十多分鐘后).有人可以解釋為什么會發生這種情況以及我做錯了什么嗎?此外,如果您在我提供的代碼中看到任何其他內容,我們將不勝感激,因為我是使用 JWT 和這個庫的新手.
I tested this and so far it still hasn't expired (After more than ten minutes). Can someone please explain why this is happening and what I am doing wrong? Also, if you see anything else with the code I provided any guidance would be appreciated since I am new to using JWTs and this library.
推薦答案
閱讀@Denis Kucherov 的回答后,我發現我可以使用他發布的同一個自定義驗證器,而無需使用需要我添加的 JwtBearerOptions 類一個新的圖書館.
After reading through @Denis Kucherov's answer, I found out that I could use the same custom validator he posted without using the JwtBearerOptions class which would have required me to add a new library.
另外,由于有兩個命名空間包含許多相同的類,我將確保提到所有這些都使用 System.IdentityModels... 命名空間.(不是 Microsoft.IdentityModels...)
Also, Since there are two namespaces which contain a lot of these same classes I will make sure to mention that all of these are using the System.IdentityModels... namespaces. (NOT Microsoft.IdentityModels...)
下面是我最終使用的代碼:
Below is the code I ended up using:
private bool CustomLifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken tokenToValidate, TokenValidationParameters @param)
{
if (expires != null)
{
return expires > DateTime.UtcNow;
}
return false;
}
private JwtSecurityToken ValidateJwtToken(string tokenString)
{
string secret = ConfigurationManager.AppSettings["jwtSecret"].ToString();
var securityKey = new InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret));
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters validation = new TokenValidationParameters()
{
ValidAudience = "MyAudience",
ValidIssuer = "MyIssuer",
ValidateIssuer = true,
ValidateLifetime = true,
LifetimeValidator = CustomLifetimeValidator,
RequireExpirationTime = true,
IssuerSigningKey = securityKey,
ValidateIssuerSigningKey = true,
};
SecurityToken token;
ClaimsPrincipal principal = handler.ValidateToken(tokenString, validation, out token);
return (JwtSecurityToken)token;
}
這篇關于JwtSecurityToken 不會過期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!