繁体   English   中英

如何使用 System.IdentityModel.Tokens.Jwt package 提取令牌过期时间

[英]How to extract the token expiration time with the System.IdentityModel.Tokens.Jwt package

我想在我的 .NET Core 项目中使用 JSON web 令牌进行身份验证。 这就是我添加System.IdentityModel.Tokens.Jwt package 的原因。

我熟悉JavaScript 等效jsonwebtoken package ,它提供了verify function 来验证和解码令牌。

大多数时候我只需要提取有效负载来获取用户和其他信息,但在某些情况下,我还需要知道令牌何时过期(例如,通过将令牌存储到数据库并在过期后将其删除来使令牌失效) .

我从这个示例代码开始

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);
}

正如您在此处看到的,我正在尝试提取令牌到期时间和有效负载。 我认为有效载荷应该可以正常工作,但我怎样才能提取到期信息?

从您的示例代码中,您应该能够获得到期时间:

tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken validatedToken);

var tokenExpiresAt = validatedToken.ValidTo;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM