【问题标题】:JWT Token Expiration time failing .net core [duplicate]JWT令牌过期时间失败.net核心[重复]
【发布时间】:2019-08-04 14:45:13
【问题描述】:

我正在尝试通过 .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 中得到了正确的值。

但是一分钟后,我在 Postman 中设置了相同的授权令牌,它就可以工作了。 如果令牌已过期,则不应。

我使用不记名令牌作为身份验证。

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

【问题讨论】:

  • 您是否检查了本地日期时间值而不是 UTC 值?
  • 我有当地时间给出了以下问题: - expires 自动采用 UTC 时间,无论我使用什么。
  • @AbhilashGopalakrishna 始终使用带有令牌的 UTC 时间,而不是本地时间

标签: asp.net-web-api .net-core jwt access-token refresh-token


【解决方案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 expired
} 

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

【讨论】:

  • .net 框架带来的超级烦人的重大变化 :(
  • 还有任何其他文档吗? 300 秒是一个相当高的数字。
猜你喜欢
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2020-08-24
  • 2016-11-13
  • 2017-10-13
  • 2020-02-16
  • 2017-06-22
  • 2019-04-18
相关资源
最近更新 更多