【问题标题】:ASP NET Core JWT authentication allows expired tokensASP NET Core JWT 身份验证允许过期令牌
【发布时间】:2019-02-22 02:13:53
【问题描述】:

由于某种原因,我的 RESTful 应用程序允许来自 Angular 客户端的请求带有过期令牌一段时间。 生成令牌:

private async Task<string> GenerateJwtToken(ApplicationUser user)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id)
    };
    claims.AddRange(await _userManager.GetClaimsAsync(user));
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("SigningKey").Value));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var expires = 
        DateTime.Now.AddSeconds(10);
        //DateTime.Now.AddDays(Convert.ToDouble(_configuration["ExpireDays"]));

    var token = new JwtSecurityToken(
        issuer: _configuration["Issuer"],
        audience: _configuration["Audience"],
        claims: claims,
        expires: expires,
        signingCredentials: creds);
    return new JwtSecurityTokenHandler().WriteToken(token);
}

在请求之前我在客户端上记录过期时间,现在以及如果现在超过过期时间。记录两个成功的请求,但最后一个应该是失败的

t:2018 年 9 月 18 日星期二 08:53:43 GMT+0300(莫斯科标准时间) 凭据-service.ts:101

现在:2018 年 9 月 18 日星期二 08:53:41 GMT+0300(莫斯科标准时间) 凭据-service.ts:102

true 表示过期

credentials-service.ts:100 t:2018 年 9 月 18 日星期二 08:53:43 GMT+0300 (莫斯科标准时间)

credentials-service.ts:101 现在:2018 年 9 月 18 日星期二 08:58:01 GMT+0300 (莫斯科标准时间)

凭证-service.ts:102

是的

由于某种原因,我在 5-6 分钟后才被拒绝,而不是 10 秒。

【问题讨论】:

  • 在令牌验证设置中找到 ClockSkew 设置 ;) 这些通常会留出一点休息时间来解决服务器时钟不同步的问题。
  • 您应该使用 ClockSkew,例如此处所示 - stackoverflow.com/questions/46129183/…

标签: c# angular asp.net-core asp.net-core-webapi


【解决方案1】:

在 Startup.cs 中定义 TokenValidationParameters 时,将属性 ClockSkew 的 TimeSpan 值设置为零:

ClockSkew = TimeSpan.Zero,例如:

new TokenValidationParameters
                {
                    IssuerSigningKey = signingKey,
                    ValidIssuer = issuer,
                    ValidAudience = audience,
                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                };

原因是 ClockSkew 的默认值为 5 分钟

【讨论】:

  • 我的英雄!-------
猜你喜欢
  • 2017-09-11
  • 2023-04-01
  • 1970-01-01
  • 2020-04-04
  • 2017-10-30
  • 1970-01-01
  • 2019-04-16
  • 2021-12-17
相关资源
最近更新 更多