ASP NET核心JWT身份验证允许过期的令牌

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

出于某种原因,我的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:Tue Sep 18 2018 08:53:43 GMT + 0300(莫斯科标准时间)credentials-service.ts:101

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

true表示已过期

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

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

凭证-service.ts:102

真正

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

c# angular asp.net-core asp.net-core-webapi
1个回答
8
投票

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

ClockSkew = TimeSpan.Zero,例如:

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

                    ClockSkew = TimeSpan.Zero
                };

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

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