Eintoo/GameServer/Server/Hotfix/Outter/Authentication/JWT/AuthenticationJWTComponentSystem.cs

83 lines
3.0 KiB
C#
Raw 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.ComponentModel;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using Fantasy;
using Fantasy.Async;
using Fantasy.Entitas.Interface;
using Fantasy.Helper;
using Microsoft.IdentityModel.Tokens;
namespace Hotfix;
public class AuthenticationJWTComponentAwakeSystem : AwakeSystem<AuthenticationJWTComponent>
{
protected override void Awake(AuthenticationJWTComponent self)
{
try
{
var rsa = RSA.Create(2048);
// 处理公钥 - 使用您提供的格式
string publicKeyData = self.PublicKey
.Replace("-----BEGIN PUBLIC KEY-----", "")
.Replace("-----END PUBLIC KEY-----", "")
.Replace("\n", "")
.Trim();
// 处理私钥 - 使用您提供的格式
string privateKeyData = self.PrivateKey
.Replace("-----BEGIN PRIVATE KEY-----", "")
.Replace("-----END PRIVATE KEY-----", "")
.Replace("\n", "")
.Trim();
var publicKeyByte = Convert.FromBase64String(publicKeyData);
var privateKeyByte = Convert.FromBase64String(privateKeyData);
// 根据您提供的密钥格式,尝试正确的导入方法
rsa.ImportSubjectPublicKeyInfo(publicKeyByte, out _);
rsa.ImportPkcs8PrivateKey(privateKeyByte, out _);
var rsaSecurityKey = new RsaSecurityKey(rsa);
self.JwtSigningCredentials = new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256);
Log.Info("RSA密钥导入成功");
}
catch (Exception ex)
{
Log.Error($"RSA密钥处理错误: {ex.Message}");
if (ex.InnerException != null)
Log.Error($"内部错误: {ex.InnerException.Message}");
}
}
}
public static class AuthenticationJWTComponentSystem
{
public static string GenerateToken(this AuthenticationJWTComponent self,long accountId)
{
var header = new JwtHeader(self.JwtSigningCredentials);
var serverGatesAddress = ServerDataConfigHelper.GateAllServerData(SceneType.Gate);
var gateAddress = serverGatesAddress[(int)(accountId % serverGatesAddress.Count)] ;
var payload = new JwtPayload()
{
{"aid",accountId},
{"gateAddress",gateAddress},
};
var jwt = new JwtSecurityToken(
issuer: "July", // 令牌发行者
audience: "gameUser", // 令牌接收者
claims: payload.Claims, // 令牌声明(包含自定义数据)
expires: DateTime.UtcNow.AddSeconds(10), // 令牌过期时间24小时后
notBefore: DateTime.UtcNow, // 令牌生效时间(立即生效)
signingCredentials: self.JwtSigningCredentials // 签名凭证使用RSA加密
);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(jwt);
}
}