JwtSecurityToken doesn't expire when it should

后端 未结 6 1945
耶瑟儿~
耶瑟儿~ 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:34

    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.

    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;
    }
    

提交回复
热议问题