修改协议工具

This commit is contained in:
2025-07-27 23:46:43 +08:00
parent 743c1d2baa
commit be33e12b35
112 changed files with 1021 additions and 1119 deletions

View File

@@ -0,0 +1,55 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using Fantasy;
using Fantasy.Entitas.Interface;
using Microsoft.IdentityModel.Tokens;
namespace NB.Authentication.Jwt;
public sealed class AuthenticationJwtComponentAwakeSystem : AwakeSystem<AuthenticationJwtComponent>
{
protected override void Awake(AuthenticationJwtComponent self)
{
self.Awake();
}
}
public static class AuthenticationJwtComponentSystem
{
public static void Awake(this AuthenticationJwtComponent self)
{
var rsa = RSA.Create();
rsa.ImportRSAPublicKey(Convert.FromBase64String(self.PublicKeyPem), out _);
rsa.ImportRSAPrivateKey(Convert.FromBase64String(self.PrivateKeyPem), out _);
self.SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256);
// 创建 TokenValidationParameters 对象,用于配置验证参数
self.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = false, // 禁止令牌验证时间是否过期
ValidateIssuer = true, // 验证发行者
ValidateAudience = true, // 验证受众
ValidateIssuerSigningKey = true, // 验证签名密钥
ValidIssuer = "Fantasy", // 有效的发行者
ValidAudience = "Fantasy", // 有效的受众
IssuerSigningKey = new RsaSecurityKey(rsa) // RSA公钥作为签名密钥
};
}
public static string GetToken(this AuthenticationJwtComponent self, long aId, string address, uint sceneId)
{
var jwtPayload = new JwtPayload()
{
{ "aId", aId },
{ "Address", address },
{ "SceneId", sceneId }
};
var jwtSecurityToken = new JwtSecurityToken(
issuer: "Fantasy",
audience: "Fantasy",
claims: jwtPayload.Claims,
expires: DateTime.UtcNow.AddMilliseconds(3000),
signingCredentials: self.SigningCredentials);
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
}

View File

@@ -0,0 +1,19 @@
using Fantasy;
namespace NB.Authentication.Jwt;
public static class AuthenticationJwtHelper
{
/// <summary>
/// 获取一个新的令牌
/// </summary>
/// <param name="scene"></param>
/// <param name="aId">AccountId</param>
/// <param name="address">目标服务器的地址</param>
/// <param name="sceneId">分配的Scene的Id</param>
/// <returns></returns>
public static string GetToken(Scene scene, long aId, string address, uint sceneId)
{
return scene.GetComponent<AuthenticationJwtComponent>().GetToken(aId, address, sceneId);
}
}