所有都用SimApiUitl.Json,增加了Gate,auth增加了获取所有token

This commit is contained in:
2026-05-03 19:34:47 +08:00
parent 894d6930f7
commit e3fc7db01c
16 changed files with 236 additions and 34 deletions
+4 -5
View File
@@ -14,7 +14,6 @@ namespace SimApi.CoceSdk;
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache) public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
{ {
/// <summary> /// <summary>
/// 获取Level Token /// 获取Level Token
/// </summary> /// </summary>
@@ -164,7 +163,7 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey); var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
logger.LogDebug("签名: {Sign}", sign); logger.LogDebug("签名: {Sign}", sign);
request.Add("sign", sign); request.Add("sign", sign);
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, JsonSerializer.Serialize(request)); logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, SimApiUtil.Json(request));
var http = new HttpClient(); var http = new HttpClient();
return http.PostAsJsonAsync(platUrl, request).Result; return http.PostAsJsonAsync(platUrl, request).Result;
} }
@@ -178,7 +177,7 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
public IEnumerable<GroupInfo>? GetUserGroups(string token) public IEnumerable<GroupInfo>? GetUserGroups(string token)
{ {
const string uri = "/api/lv2/user/groups"; const string uri = "/api/lv2/user/groups";
var resp = ProxyQuery<GroupInfo[]>(uri, token,"{}"); var resp = ProxyQuery<GroupInfo[]>(uri, token, "{}");
return resp; return resp;
} }
@@ -207,10 +206,10 @@ public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDist
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json); public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
public dynamic? ProxyQueue(string uri, string token, object data) => public dynamic? ProxyQueue(string uri, string token, object data) =>
ProxyQuery<dynamic>(uri, token, JsonSerializer.Serialize(data)); ProxyQuery<dynamic>(uri, token, SimApiUtil.Json(data));
public T? ProxyQueue<T>(string uri, string token, object data) => public T? ProxyQueue<T>(string uri, string token, object data) =>
ProxyQuery<T>(uri, token, JsonSerializer.Serialize(data)); ProxyQuery<T>(uri, token, SimApiUtil.Json(data));
public T? ProxyQuery<T>(string uri, string token, string json = "{}") public T? ProxyQuery<T>(string uri, string token, string json = "{}")
{ {
+1 -1
View File
@@ -10,5 +10,5 @@ public class SimApiLoginItem
public required string Id { get; set; } public required string Id { get; set; }
public string[] Type { get; set; } = ["user"]; public string[] Type { get; set; } = ["user"];
public Dictionary<string, string> Meta { get; set; } = []; public Dictionary<string, string> Meta { get; set; } = [];
public object? Extra { get; set; } public Dictionary<string, object?> Extra { get; set; } = [];
}; };
+8
View File
@@ -0,0 +1,8 @@
namespace SimApi.Configurations;
public class SimApiGateAuthOptions
{
public string? AppId { get; set; }
public string? AppKey { get; set; }
}
+12 -1
View File
@@ -18,6 +18,11 @@ public class SimApiOptions
/// </summary> /// </summary>
public bool EnableSimApiAuth { get; set; } public bool EnableSimApiAuth { get; set; }
/// <summary>
/// 启用SimApi网关授权, 基于上层网关透传的身份令牌验证
/// </summary>
public bool EnableSimApiGateAuth { get; set; }
/// <summary> /// <summary>
/// 是否使用CoceSdk /// 是否使用CoceSdk
/// </summary> /// </summary>
@@ -81,7 +86,6 @@ public class SimApiOptions
public bool EnableVersionUrl { get; set; } = true; public bool EnableVersionUrl { get; set; } = true;
/// <summary> /// <summary>
/// 启用格式化的 Console Logger /// 启用格式化的 Console Logger
/// default: false /// default: false
@@ -106,6 +110,8 @@ public class SimApiOptions
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new(); public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
public SimApiGateAuthOptions SimApiGateAuthOptions { get; set; } = new();
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null) public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
{ {
options?.Invoke(SimApiSynapseOptions); options?.Invoke(SimApiSynapseOptions);
@@ -130,4 +136,9 @@ public class SimApiOptions
{ {
options?.Invoke(SimApiJobOptions); options?.Invoke(SimApiJobOptions);
} }
public void ConfigureSimApiGateAuth(Action<SimApiGateAuthOptions>? options = null)
{
options?.Invoke(SimApiGateAuthOptions);
}
} }
+2
View File
@@ -23,6 +23,8 @@ public class SimApiBaseController : Controller
/// </summary> /// </summary>
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!; protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
protected SimApiLoginItem LoginToken => (SimApiLoginItem)HttpContext.Items["LoginToken"]!;
/// <summary> /// <summary>
/// 验证请求参数 /// 验证请求参数
/// </summary> /// </summary>
+94 -10
View File
@@ -1,25 +1,42 @@
using System; using System;
using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications; using SimApi.Communications;
using StackExchange.Redis;
namespace SimApi.Helpers; namespace SimApi.Helpers;
/// <summary> /// <summary>
/// 认证助手 /// 认证助手
/// </summary> /// </summary>
public class SimApiAuth(IDistributedCache cache) public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
{ {
private const string TokenCacheKey = "SimApi:Auth:Token:{token}";
private const string TokenSetCacheKey = "SimApi:Auth:User:{userId}";
private readonly IDatabase _redisDb = redis.GetDatabase();
/// <summary> /// <summary>
/// 登录信息 /// 登录信息
/// </summary> /// </summary>
/// <param name="loginItem"></param> /// <param name="loginItem"></param>
/// <param name="expireTime"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
public string Login(SimApiLoginItem loginItem, string? token = null) public string Login(SimApiLoginItem loginItem, TimeSpan? expireTime = null, string? token = null)
{ {
expireTime ??= TimeSpan.FromDays(7);
token ??= Guid.NewGuid().ToString(); token ??= Guid.NewGuid().ToString();
cache.SetString(token, JsonSerializer.Serialize(loginItem)); var cacheKey = TokenCacheKey.Replace("{token}", token);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.SetAdd(setCacheKey, token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem),
new DistributedCacheEntryOptions
{
SlidingExpiration = expireTime
});
_redisDb.KeyExpire(setCacheKey, expireTime.Value);
return token; return token;
} }
@@ -31,10 +48,15 @@ public class SimApiAuth(IDistributedCache cache)
/// <returns></returns> /// <returns></returns>
public string Update(SimApiLoginItem loginItem, string token) public string Update(SimApiLoginItem loginItem, string token)
{ {
cache.SetString(token, JsonSerializer.Serialize(loginItem)); var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.SetString(cacheKey, SimApiUtil.Json(loginItem));
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", loginItem.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
return token; return token;
} }
/// <summary> /// <summary>
/// 获取登陆信息 /// 获取登陆信息
/// </summary> /// </summary>
@@ -42,19 +64,81 @@ public class SimApiAuth(IDistributedCache cache)
/// <returns></returns> /// <returns></returns>
public SimApiLoginItem? GetLogin(string token) public SimApiLoginItem? GetLogin(string token)
{ {
var login = cache.GetString(token); var cacheKey = TokenCacheKey.Replace("{token}", token);
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null; var login = cache.GetString(cacheKey);
var resp = login != null ? SimApiUtil.FromJson<SimApiLoginItem>(login) : null;
if (resp != null)
{
var ttl = _redisDb.KeyTimeToLive(cacheKey);
var setCacheKey = TokenSetCacheKey.Replace("{userId}", resp.Id);
_redisDb.KeyExpire(setCacheKey, ttl);
}
return resp;
}
/// <summary>
/// 获取所有的登录token
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public SimApiLoginItem[] GetAllLogins(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
var resp = new List<SimApiLoginItem>();
foreach (var login in allLogins)
{
if (login != null)
{
var item = GetLogin(login);
if (item != null)
{
resp.Add(item);
}
else
{
_redisDb.SetRemove(setCacheKey, login);
}
}
}
return resp.ToArray();
}
/// <summary>
/// 退出所有登录
/// </summary>
/// <param name="userId"></param>
public void LogoutAll(string userId)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", userId);
var allLogins = _redisDb.SetMembers(setCacheKey).ToStringArray();
foreach (var login in allLogins)
{
if (login != null)
{
var cacheKey = TokenCacheKey.Replace("{token}", login);
cache.Remove(cacheKey);
}
}
_redisDb.KeyDelete(setCacheKey);
} }
/// <summary> /// <summary>
/// 退出登陆 /// 退出登陆
/// </summary> /// </summary>
/// <param name="uuid">登陆标识</param> /// <param name="token">登陆标识</param>
public void Logout(string uuid) public void Logout(string token)
{ {
if (!string.IsNullOrEmpty(uuid)) var item = GetLogin(token);
if (item != null)
{ {
cache.Remove(uuid); var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
_redisDb.SetRemove(setCacheKey, token);
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.Remove(cacheKey);
} }
} }
} }
+45
View File
@@ -151,6 +151,51 @@ public static class SimApiUtil
return sb.ToString(); return sb.ToString();
} }
/// <summary>
/// 字符串Base64编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Encode(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// 从Base64中解码字符串
/// </summary>
/// <param name="base64Str"></param>
/// <returns></returns>
public static string Base64Decode(string base64Str)
{
var bytes = Convert.FromBase64String(base64Str);
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// 把对象Base64编码
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string Base64Encode(object obj)
{
var json = Json(obj);
return Base64Encode(json);
}
/// <summary>
/// 从Base64中解析对象
/// </summary>
/// <param name="base64Str"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T? Base64Decode<T>(string base64Str)
{
var json = Base64Decode(base64Str);
return FromJson<T>(json);
}
/// <summary> /// <summary>
/// 将XML字符串序列化为对象 /// 将XML字符串序列化为对象
/// </summary> /// </summary>
+4 -5
View File
@@ -1,8 +1,5 @@
using System.Text.Json; using System.Threading.Tasks;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
using SimApi.Helpers; using SimApi.Helpers;
namespace SimApi.Middlewares; namespace SimApi.Middlewares;
@@ -12,7 +9,7 @@ namespace SimApi.Middlewares;
/// </summary> /// </summary>
public class SimApiAuthMiddleware(RequestDelegate next) public class SimApiAuthMiddleware(RequestDelegate next)
{ {
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth) public Task Invoke(HttpContext httpContext, SimApiAuth auth)
{ {
string? token = null; string? token = null;
if (httpContext.Request.Headers.TryGetValue("Token", out var header)) if (httpContext.Request.Headers.TryGetValue("Token", out var header))
@@ -24,8 +21,10 @@ public class SimApiAuthMiddleware(RequestDelegate next)
var login = auth.GetLogin(token); var login = auth.GetLogin(token);
if (login != null) if (login != null)
{ {
httpContext.Items.Add("LoginToken", token);
httpContext.Items.Add("LoginInfo", login); httpContext.Items.Add("LoginInfo", login);
} }
return next(httpContext); return next(httpContext);
} }
} }
+4 -2
View File
@@ -29,9 +29,10 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
case 200: case 200:
case 301: case 301:
case 302: case 302:
break;
case 404: case 404:
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在"); break;
// case 404:
// throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
default: default:
throw new SimApiException(context.Response.StatusCode); throw new SimApiException(context.Response.StatusCode);
} }
@@ -79,6 +80,7 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
context.Response.StatusCode = 200; context.Response.StatusCode = 200;
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
context.Response.ContentLength = null; // 清除可能已设置的 Content-Length
await context.Response.WriteAsync(response.ToString()); await context.Response.WriteAsync(response.ToString());
} }
} }
+35
View File
@@ -0,0 +1,35 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SimApi.Communications;
using SimApi.Configurations;
using SimApi.Helpers;
namespace SimApi.Middlewares;
public class SimApiGateAuthMiddleware(RequestDelegate next, ILogger<SimApiGateAuthMiddleware> logger)
{
public Task Invoke(HttpContext httpContext, SimApiOptions simApiOptions)
{
if (httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Auth", out var auth) &&
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Time", out var time) &&
httpContext.Request.Headers.TryGetValue("X-SimApi-Gate-Sign", out var sign))
{
var signStr =
$"appId={simApiOptions.SimApiGateAuthOptions.AppId}&auth={auth}&time={time}&appKey={simApiOptions.SimApiGateAuthOptions.AppKey}";
logger.LogDebug($"签名字符串 => {signStr}");
if (SimApiUtil.Md5(signStr) == sign && !string.IsNullOrEmpty(auth))
{
var login = SimApiUtil.Base64Decode<SimApiLoginItem>(auth!);
httpContext.Items.Add("LoginInfo", login);
}
else
{
logger.LogDebug("签名不匹配");
}
}
return next(httpContext);
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ public class AesBodyModelBinder : IModelBinder
SimApiOneFieldRequest<string>? aesRequest; SimApiOneFieldRequest<string>? aesRequest;
try try
{ {
aesRequest = JsonSerializer.Deserialize<SimApiOneFieldRequest<string>>(requestBody, SimApiUtil.JsonOption); aesRequest = SimApiUtil.FromJson<SimApiOneFieldRequest<string>>(requestBody);
} }
catch (JsonException ex) catch (JsonException ex)
{ {
+17
View File
@@ -20,6 +20,7 @@ using SimApi.CoceSdk;
using SimApi.Configurations; using SimApi.Configurations;
using SimApi.Logger; using SimApi.Logger;
using SimApi.SwaggerFilters; using SimApi.SwaggerFilters;
using StackExchange.Redis;
namespace SimApi; namespace SimApi;
@@ -37,6 +38,8 @@ public static class SimApiExtensions
if (simApiOptions.RedisConfiguration != null) if (simApiOptions.RedisConfiguration != null)
{ {
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration); builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
builder.AddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(simApiOptions.RedisConfiguration));
builder.AddSingleton<SimApiCache>(); builder.AddSingleton<SimApiCache>();
} }
@@ -391,6 +394,20 @@ public static class SimApiExtensions
builder.MapControllers(); builder.MapControllers();
} }
if (options.EnableSimApiGateAuth)
{
logger.LogInformation("开始配置SimApiGateAuth...");
if (string.IsNullOrEmpty(options.SimApiGateAuthOptions.AppId) ||
string.IsNullOrEmpty(options.SimApiGateAuthOptions.AppKey))
{
logger.LogCritical("必须配置Gate的AppId和AppKey才能启用SimApiGateAuth");
}
else
{
builder.UseMiddleware<SimApiGateAuthMiddleware>();
}
}
if (options.EnableSimApiAuth) if (options.EnableSimApiAuth)
{ {
logger.LogInformation("开始配置SimApiAuth..."); logger.LogInformation("开始配置SimApiAuth...");
+2 -1
View File
@@ -17,8 +17,9 @@ public partial class Synapse
} }
else else
{ {
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption); paramJson = SimApiUtil.Json(param);
} }
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}"; var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
var message = new MqttApplicationMessageBuilder() var message = new MqttApplicationMessageBuilder()
.WithTopic(topic) .WithTopic(topic)
+4 -5
View File
@@ -50,7 +50,7 @@ public partial class Synapse
} }
else else
{ {
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption); paramJson = SimApiUtil.Json(param);
} }
var topic = $"{Options.SysName}/{app}/rpc/server/{action}"; var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
@@ -73,7 +73,7 @@ public partial class Synapse
Client.PublishAsync(message, CancellationToken.None).Wait(); Client.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug( logger.LogDebug(
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}", "Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers)); messageId, Options.AppName, action, app, paramJson, SimApiUtil.Json(headers));
string response; string response;
try try
@@ -88,13 +88,12 @@ public partial class Synapse
} }
else else
{ {
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption); response = SimApiUtil.Json(new SimApiBaseResponse(502, "timeout"));
} }
} }
catch catch
{ {
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"), response = SimApiUtil.Json(new SimApiBaseResponse(500, "Synapse RPC Client Error"));
SimApiUtil.JsonOption);
} }
return response; return response;
+2 -2
View File
@@ -10,7 +10,7 @@ using MQTTnet.Protocol;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Exceptions; using SimApi.Exceptions;
using SimApi.Helpers; using SimApi.Helpers;
using JsonSerializer = System.Text.Json.JsonSerializer; using System.Text.Json;
namespace SimApi; namespace SimApi;
@@ -96,7 +96,7 @@ public partial class Synapse
} }
} }
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption); var returnJson = SimApiUtil.Json(res);
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}"; var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
var message = new MqttApplicationMessageBuilder() var message = new MqttApplicationMessageBuilder()
.WithTopic(reply) .WithTopic(reply)
+1 -1
View File
@@ -101,7 +101,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
else else
{ {
var data = FireRpc(appName, method, param, headers, timeout); var data = FireRpc(appName, method, param, headers, timeout);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption); res = SimApiUtil.FromJson<SimApiBaseResponse<T>>(data);
} }
return (res as SimApiBaseResponse<T>)!; return (res as SimApiBaseResponse<T>)!;