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 { 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($"Gate:Token签名校验成功"); payload = tokenHandler.ReadJwtToken(token).Payload; //return GameErrorCode.GateTokenValidSuccess; return true; } catch (SecurityTokenExpiredException) { Log.Warning($"Gate:Token已过期"); return false; //return GameErrorCode.GateTokenExpired; } catch (SecurityTokenInvalidSignatureException) { Log.Warning($"Gate:Token签名无效"); return false; //return GameErrorCode.GateTokenInvalidSignature; } catch (Exception e) { Log.Error($"Gate:Token验证失败: {e.Message}"); return false; //return GameErrorCode.GateTokenGeneralError; } } }