【问题标题】:.NET JWT Implementation accepting expired tokens.NET JWT 实现接受过期令牌
【发布时间】:2020-12-21 01:39:48
【问题描述】:

我正在我的 API 中生成一个有效的 JWT,并返回它并嵌入一个过期时间。请参阅下面的代码和示例:

    public static string GenerateToken(string securityKey,
        string claimName, string issuer, RedisManagerPool redisClient)
    {
        var claims = new[]
            {
                new Claim(ClaimTypes.Name,
                claimName)
            };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var expiry = DateTime.Now.AddMinutes(UtilityCommand.Cache.GetCacheValue<int>(Functions.ParameterPath 
            + Functions.Integration 
            + Functions.JWT 
            + "/expiry_minutes", redisClient));

        var token = new JwtSecurityToken(
            issuer: issuer,
            audience: issuer,
            claims: claims,
            expires: expiry,
            signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

例子:

{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "scpi",
  "exp": 1598960076,
  "iss": "https://lcsapi",
  "aud": "https://lcsapi"
}

但是无论我使用令牌多久,它都不会过期?我在哪里错了?即使我将到期时间设置为 1 分钟。这是我的身份验证检查:

    public APIGatewayCustomAuthorizerResponse GetAuthentication(APIGatewayCustomAuthorizerRequest authorizerRequest, ILambdaContext context)
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = Issuer,
            ValidateAudience = true,
            ValidateLifetime = UtilityCommand.Cache.GetCacheValue<bool>(ParameterPath + Integration + JWT + "/jwtexpires", _redisClient), // testing
            ValidAudience = Issuer,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey)),
            ClockSkew = TimeSpan.FromMinutes(5), // Required to account for potential drift times between systems. 
            ValidateIssuerSigningKey = true
        };

        SecurityToken validatedToken;

        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
        bool authorized = false;

        if (!string.IsNullOrWhiteSpace(authorizerRequest.AuthorizationToken))
        {
            try
            {
                var jwt = authorizerRequest.AuthorizationToken.Replace("Bearer ", string.Empty);
                var user = handler.ValidateToken(jwt, tokenValidationParameters, out validatedToken);
                var claim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
                if (claim != null)
                    authorized = claim.Value == ClaimName; // Ensure that the claim value matches the assertion
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"Error occurred validating token: {ex.Message}");
            }
        }
        else
        {
            context.Logger.LogLine($"Error occurred validating token: No token provided.");
        }

        return GenerateAuthorizerResponse(authorized, authorizerRequest, context);
    }

【问题讨论】:

    标签: c# jwt access-token


    【解决方案1】:

    很高兴您已解决。值得确保您根据 DateTime.UtcNow 检查到期时间,因为到期声明是 UTC 值。

    【讨论】:

      【解决方案2】:

      回答,我需要将以下内容添加到我的 TokenValidationParameters。

      LifetimeValidator = LifetimeValidator,
      

      它接受一个检查到期的委托函数(我没有意识到这不是自动处理的)。它只是一个关于是否过期的布尔返回:

      private bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken token, TokenValidationParameters @params)
      {
          if (expires != null)
          {
              return expires > DateTime.Now;
          }
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-07
        • 2021-11-04
        • 1970-01-01
        • 2017-03-04
        • 2019-07-04
        • 1970-01-01
        • 2019-12-22
        • 2017-08-20
        • 2018-06-19
        相关资源
        最近更新 更多