JWT令牌到期时间失败.net核心

问题描述 投票:0回答:1

我试图通过刷新令牌和.NET Core 2.1中的JWT来实现基于令牌的身份验证。

这就是我实现JWT令牌的方式:

Startup.cs

services.AddAuthentication(option =>
    {
        option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.SaveToken = true;
        options.RequireHttpsMetadata = true;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidAudience = Configuration["Jwt:Site"],
            ValidIssuer = Configuration["Jwt:Site"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SigningKey"]))
        };

        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                {
                    context.Response.Headers.Add("Token-Expired", "true");
                }
                return Task.CompletedTask;
            }
        };
    });

令牌生成:

var jwt = new JwtSecurityToken(
                issuer: _configuration["Jwt:Site"],
                audience: _configuration["Jwt:Site"],
                expires: DateTime.UtcNow.AddMinutes(1),
                signingCredentials: new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
                );

        return new TokenReturnViewModel()
        {
            token = new JwtSecurityTokenHandler().WriteToken(jwt),
            expiration = jwt.ValidTo,
            currentTime = DateTime.UtcNow
        };

我在Response中获得了正确的值。

enter image description here

但过了一会儿,我在Postman中为授权设置了相同的令牌并且它有效。如果令牌已过期,则不应该。

我使用承载令牌作为身份验证。

我究竟做错了什么?需要方向。

asp.net-web-api .net-core jwt access-token refresh-token
1个回答
1
投票

有一个名为ClockSkew的令牌验证参数,它可以获取或设置在验证时间时应用的时钟偏差。 ClockSkew的默认值为5分钟。这意味着如果您没有设置它,您的令牌将在5分钟内仍然有效。

如果你想在准确的时间到期你的令牌;您需要将ClockSkew设置为零,如下所示,

options.TokenValidationParameters = new TokenValidationParameters()
{
    //other settings
    ClockSkew = TimeSpan.Zero
};

另一种方法,创建自定义AuthorizationFilter并手动检查。

var principal = ApiTokenHelper.GetPrincipalFromToken(token);
var expClaim = principal.Claims.First(x => x.Type == "exp").Value;
var tokenExpiryTime = Convert.ToDouble(expClaim).UnixTimeStampToDateTime();
if (tokenExpiryTime < DateTime.UtcNow)
{
  //return token expried
} 

这里,GetPrincipalFromTokenApiTokenHelper类的自定义方法,它将返回您在发出令牌时存储的ClaimsPrincipal值。

© www.soinside.com 2019 - 2024. All rights reserved.