JwtSecurityToken doesn't expire when it should

后端 未结 6 1938
耶瑟儿~
耶瑟儿~ 2021-02-02 07:55

I am currently using the JwtSecurityToken class in System.IdentityModels.Tokens namespace. I create a token using the following:

DateTime expires = DateTime.Utc         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 08:42

    There are seems to be some issue with LifeTimeValidator. You can just override its logic with a custom delegate. Also, use JwtBearerOptions class to control authentication middleware behavior. For example:

    new JwtBearerOptions
    {
         AutomaticAuthenticate = true,
         AutomaticChallenge = true,
         TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
         {
               ValidIssuer = _configuration["Tokens:Issuer"],
               ValidAudience = _configuration["Tokens:Audience"],
               ValidateIssuer = true,
               ValidateAudience = true,
               ValidateLifetime = true,
               LifetimeValidator = LifetimeValidator,
               ValidateIssuerSigningKey = true,
               IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]))
          }
    }
    

    And assign LifetimeValidotor delegate, to provide its own timeout validation logic:

    private bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken token, TokenValidationParameters @params)
    {
         if (expires != null)
         {
              return expires > DateTime.UtcNow;
         }
         return false;
    }
    

提交回复
热议问题