You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.4 KiB
47 lines
1.4 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace AIK.Common.SysCommon.UserCommon
|
|
{
|
|
public static class UserTokenHelper
|
|
{
|
|
public static (bool Success, long? UserId, long? Exp) ParseJwtPayload(string jwt)
|
|
{
|
|
try
|
|
{
|
|
var parts = jwt.Split('.');
|
|
if (parts.Length != 3) return (false, null, null);
|
|
|
|
var payloadJson = Base64UrlDecode(parts[1]);
|
|
using var doc = JsonDocument.Parse(payloadJson);
|
|
var root = doc.RootElement;
|
|
|
|
long? userId = root.TryGetProperty("userId", out var uid) ? uid.GetInt64() : null;
|
|
long? exp = root.TryGetProperty("exp", out var e) ? e.GetInt64() : null;
|
|
|
|
return (true, userId, exp);
|
|
}
|
|
catch
|
|
{
|
|
return (false, null, null);
|
|
}
|
|
}
|
|
|
|
private static string Base64UrlDecode(string input)
|
|
{
|
|
// 补齐 padding
|
|
string padded = input.Replace('-', '+').Replace('_', '/');
|
|
switch (padded.Length % 4)
|
|
{
|
|
case 2: padded += "=="; break;
|
|
case 3: padded += "="; break;
|
|
}
|
|
byte[] data = Convert.FromBase64String(padded);
|
|
return System.Text.Encoding.UTF8.GetString(data);
|
|
}
|
|
}
|
|
}
|
|
|