73 lines
2.4 KiB
C#
73 lines
2.4 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Cryptography;
|
|
using Fantasy;
|
|
using Fantasy.Async;
|
|
using Fantasy.Entitas.Interface;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Hotfix;
|
|
|
|
|
|
|
|
public class GateJWTComponentAwakeSystem : AwakeSystem<GateJWTComponent>
|
|
{
|
|
protected override void Awake(GateJWTComponent self)
|
|
{
|
|
RSA rsa = RSA.Create(2048);
|
|
string publicKeyData = self.PublicKey
|
|
.Replace("-----BEGIN PUBLIC KEY-----", "")
|
|
.Replace("-----END PUBLIC KEY-----", "")
|
|
.Replace("\n", "")
|
|
.Trim();
|
|
var publicKeyBytes = Convert.FromBase64String(publicKeyData);
|
|
rsa.ImportSubjectPublicKeyInfo(publicKeyBytes,out _);
|
|
RsaSecurityKey securityKey = new RsaSecurityKey(rsa);
|
|
|
|
// 创建验证参数
|
|
self.ValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = false, // 是否验证发行者
|
|
ValidateAudience = false, // 是否验证接收者
|
|
ValidateLifetime = true, // 是否验证过期时间
|
|
ValidateIssuerSigningKey = true, // 是否验证签名密钥
|
|
IssuerSigningKey = new RsaSecurityKey(rsa)
|
|
};
|
|
}
|
|
}
|
|
public static class GateJWTComponentSystem
|
|
{
|
|
public static bool ValidateToken(this GateJWTComponent self,string token,out JwtPayload payload )
|
|
{
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
payload = null;
|
|
try
|
|
{
|
|
tokenHandler.ValidateToken(token,self.ValidationParameters, out SecurityToken validatedToken);
|
|
Log.Warning($"Token签名校验成功");
|
|
payload = tokenHandler.ReadJwtToken(token).Payload;
|
|
Log.Debug("jwtPayLoad"+ payload);
|
|
//return GameErrorCode.GateTokenValidSuccess;
|
|
return true;
|
|
}
|
|
catch (SecurityTokenExpiredException)
|
|
{
|
|
Log.Warning($"Token已过期");
|
|
return false;
|
|
//return GameErrorCode.GateTokenExpired;
|
|
}
|
|
catch (SecurityTokenInvalidSignatureException)
|
|
{
|
|
Log.Warning($"Token签名无效");
|
|
return false;
|
|
//return GameErrorCode.GateTokenInvalidSignature;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Log.Error($"Token验证失败: {e.Message}");
|
|
return false;
|
|
//return GameErrorCode.GateTokenGeneralError;
|
|
}
|
|
|
|
}
|
|
} |