JwtSecurityToken doesn't expire when it should

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

    .NET Core Update

    This is handled slightly differently in .NET Core, as the TokenValidationParameters are set in Startup.cs using the ConfigureServices() method and then handled automatically by the middleware.

    Also note that the older InMemorySymmetricSecurityKey for signing the secret is now deprecated in favor of SymmetricSecurityKey, which is shown below.

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
    
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = _config.AuthenticationSettings.TokenAuthority,
                    ValidAudience = _config.AuthenticationSettings.TokenAuthority,
                    LifetimeValidator = TokenLifetimeValidator.Validate,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(_config.AuthenticationSettings.SecurityKey))
                };
            });
    
        // ...
    }
    

    And so I also made my own version of the token validator in @tkd_aj's answer above and threw it in a static class:

    public static class TokenLifetimeValidator
    {
        public static bool Validate(
            DateTime? notBefore,
            DateTime? expires,
            SecurityToken tokenToValidate,
            TokenValidationParameters @param
        ) {
            return (expires != null && expires > DateTime.UtcNow);
        }
    }
    

提交回复
热议问题