我正在生成JWT以與我的WebApi項目一起使用。我將令牌設置爲在一分鐘內過期,以便我可以測試它是否在到期日期之後提交時拒絕令牌。.NetCore JwtBearerAuthentication不拒絕過期的令牌
CreateToken控制器
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 = awaitUserManager.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
});
}
令牌認證 - 啓動類
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 =真托克斯(Tokes)沒有否決兩分鐘後。它將繼續接受令牌。是否有最低到期時間,我不知道或者我的設置錯誤?
我不認爲你有這個代碼的可運行版本,是嗎?無論如何,我查找了'UseJwtBearerAuthentication'的文檔,看起來它已被廢棄:/ https://github.com/aspnet/Security/blob/99aa3bd35dd5fbe46a93eef8a2c8ab1f9fe8d05b/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerAppBuilderExtensions。 cs –
@MariaInesParnisari是的,我的代碼正在運行,令牌的簽發和驗證工作。除了我寫入的用於導入不對稱X509Certificate2的小型證書類以外,幾乎所有的功能都在這裏。它似乎並不總是驗證到期。我看着你的鏈接,似乎不贊成。但我沒有看到替代它的東西。 – Dblock247
我的意思是如果這個代碼在GitHub中託管,所以我可以下載它並自己嘗試。當您說驗證有效時,您是否嘗試過手動更改令牌的任何其他屬性(例如受衆)以查看驗證失敗? –