【发布时间】: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