39 lines
1.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Text;
using System.Text.Json;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// JWT 的**本地只读**小工具(只解析 payload 里的 exp,不验签)。
///
/// 后台服务用它判断「访问令牌是不是快到期了」;真正的有效性仍由服务端校验。
/// </summary>
public static class JwtUtil
{
/// <summary>取令牌的过期时间(解析不了返回 null)</summary>
public static DateTime? Expiry(string? token)
{
if (string.IsNullOrWhiteSpace(token)) return null;
try
{
var parts = token.Split('.');
if (parts.Length != 3) return null;
var payload = parts[1].Replace('-', '+').Replace('_', '/');
while (payload.Length % 4 != 0) payload += "=";
using var document = JsonDocument.Parse(Convert.FromBase64String(payload));
if (!document.RootElement.TryGetProperty("exp", out var exp)) return null;
if (!exp.TryGetInt64(out var seconds)) return null;
return DateTimeOffset.FromUnixTimeSeconds(seconds).LocalDateTime;
}
catch
{
return null;
}
}
}