簡體   English   中英

ASP.NET Core 和 JWT 令牌生命周期

[英]ASP.NET Core and JWT token lifetime

我使用ASP.NET Core 2.1.1

有趣的是,過期時間只被考慮到,當一個同時提供ClockSkew -在Startup.csJwtSecurityTokenHandler.TokenLifetimeInMinutes -在控制器

例如:

services
  .AddJwtBearer(x =>
  {
      ...
      x.TokenValidationParameters = new TokenValidationParameters()
      {
         ClockSkew = TimeSpan.FromMinutes(90),
         ...

...
public async Task<AuthenticateOutput> Authenticate([FromBody] AuthenticateInput input)
{
   var tokenHandler = new JwtSecurityTokenHandler();
   tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes;
   ...

如果我刪除tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes; part - 使用默認過期時間。

在我看來tokenHandler.TokenLifetimeInMinutes仍然是多余的,我只是誤解了如何正確設置到期時間的概念。

我還嘗試添加過期聲明 - new Claim(ClaimTypes.Expiration, ...) - 但這並沒有太大效果。

ClockSkew屬性本身不是到期,它補償了時鍾偏差

要設置令牌過期,您必須在令牌創建時指定它:

new JwtSecurityToken(
                ...
                expires: DateTime.UtcNow.AddMinutes(90),
                ....);

以下代碼將為您提供帶令牌的字符串:

var token = new JwtSecurityToken() { /* setup your token setting here*/ }
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
//reading the key from config
//reading the issuer from config
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(configuration["Jwt:Issuer"], configuration["Jwt:Issuer"], 
                            null, expires: DateTime.Now.AddMinutes(60),
                            signingCredentials: credentials); //60mins expiration 

            string newToken = new JwtSecurityTokenHandler().WriteToken(token);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM