83 lines
3.0 KiB
C#
83 lines
3.0 KiB
C#
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);
|
||
}
|
||
}
|