c# - ASP NET Core JWT 身份验证允许过期 token

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

出于某种原因,我的 RESTful 应用程序允许使用过期 token 的 Angular 客户端请求一段时间。 生成 token :

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: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time) credentials-service.ts:101

now: Tue Sep 18 2018 08:53:41 GMT+0300 (Moscow Standard Time) credentials-service.ts:102

false

true 表示已过期

credentials-service.ts:100 t: Tue Sep 18 2018 08:53:43 GMT+0300 (Moscow Standard Time)

credentials-service.ts:101 now: Tue Sep 18 2018 08:58:01 GMT+0300 (Moscow Standard Time)

credentials-service.ts:102

true

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

最佳答案

在 Startup.cs 中定义 TokenValidationParameters 的位置,为属性 ClockSkew 指定一个 TimeSpan 值为零:

ClockSkew = TimeSpan.Zero,例如:

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

                    ClockSkew = TimeSpan.Zero
                };

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

关于c# - ASP NET Core JWT 身份验证允许过期 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379848/

相关文章:

c# - 如何使用javascript乘以文本框值?

Angular Material : making a mat-card fill an entire mat-grid-tile

node.js - 部署 Angular 2 项目时,Azure 持续部署在 Github 上失败

asp.net-core - AspNetCore 命名空间不存在

c# - 无法从单例 'MyDbContext' 使用范围服务 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'

asp.net-core - 无法在 Visual Studio 2015 update 3 中通过右键单击添加 View

c# - 如何将 SwitchCell 文本颜色绑定(bind)到 Xamarin.Forms 中的 View 模型

c# - UWP - 防止 NavigationViewItemHeader 被剪裁

c# - 如何切换到特定文档的处理

Angular <mat-progress-spinner> 如何在页面加载完成时显示和隐藏