我想在我的.NET核心项目中使用JSON web令牌进行身份验证。这就是我将System.IdentityModel.Tokens.Jwt包添加到其中的原因。
我熟悉JavaScript equivalent jsonwebtoken package,它提供了一个verify函数来验证和解码令牌。
大多数情况下,我只需要提取有效负载来获取用户和其他信息,但在某些情况下,我还需要知道令牌何时过期(例如,通过将令牌存储到数据库中并在过期后将其删除来使令牌无效)。
我从下面的示例代码开始
public object ValidateAndDecodeToken(string token)
{
SymmetricSecurityKey symmetricSecurityKey = GenerateSymmetricSecurityKey("db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw=="); // From config
try
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = symmetricSecurityKey
};
tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken);
DateTime tokenExpiresAt = DateTime.Now; // TODO
JwtSecurityToken jwtSecurityToken = tokenHandler.ReadJwtToken(encodedToken);
Dictionary<string, string> tokenPayload = jwtSecurityToken.Claims.ToDictionary(claim => claim.Type, claim => claim.Value);
return new { token, tokenExpiresAt, tokenPayload };
}
catch
{
throw;
}
}
private SymmetricSecurityKey GenerateSymmetricSecurityKey(string base64Secret)
{
byte[] symmetricKey = Convert.FromBase64String(base64Secret);
return new SymmetricSecurityKey(symmetricKey);
}正如您在这里看到的,我正在尝试提取令牌过期时间和有效负载。我认为有效负载应该工作得很好,但是我如何提取到期信息?
发布于 2020-07-15 04:07:08
从示例代码中,您应该能够获得到期时间,如下所示:
tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken);
var tokenExpiresAt = validatedToken.ValidTo;https://stackoverflow.com/questions/62902754
复制相似问题