Compare commits

...
3 Commits
10 changed files with 77 additions and 63 deletions
+9 -8
View File
@@ -1,9 +1,11 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using SimApi.Communications;
using SimApi.Exceptions;
using SimApi.Interfaces;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Attributes;
@@ -37,17 +39,16 @@ public class SimApiAuthAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
{
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
//检测是否登录
if (loginInfo == null)
var token = (string)context.HttpContext.Items["LoginToken"]!;
ErrorWhenNull(loginInfo, 401);
var checkers = context.HttpContext.RequestServices.GetServices<ISimApiAuthChecker>();
foreach (var checker in checkers)
{
throw new SimApiException(401);
checker.Run(loginInfo, token);
}
if (Types == null) return;
//检测用户类型
if (!Types.Intersect(loginInfo.Type).Any())
{
throw new SimApiException(403);
}
ErrorWhenFalse(Types.Intersect(loginInfo.Type).Any(), 403);
}
}
+2 -2
View File
@@ -27,11 +27,11 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
{ 400, "参数错误" },
{ 401, "需要登录" },
{ 403, "无权访问" },
{ 404, "接口不存在" },
{ 404, "请求资源不存在" },
{ 500, "服务器错误" }
};
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误代码"))
{
}
-15
View File
@@ -9,17 +9,6 @@ using static SimApiError;
public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
{
/// <summary>
/// 检测用户登陆的控制器
/// </summary>
/// <returns></returns>
[HttpPost, SimApiDoc("认证", "检测登陆")]
public string CheckLogin()
{
ErrorWhenNull(LoginInfo, 401, "未登录");
return LoginInfo.Id;
}
/// <summary>
/// 退出登陆
/// </summary>
@@ -32,8 +21,4 @@ public class SimApiAuthController(SimApiAuth auth) : SimApiBaseController
auth.Logout(value!);
}
}
[HttpPost, SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
public SimApiLoginItem UserInfo() => LoginInfo;
}
+1 -1
View File
@@ -23,7 +23,7 @@ public class SimApiBaseController : Controller
/// </summary>
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
protected SimApiLoginItem LoginToken => (SimApiLoginItem)HttpContext.Items["LoginToken"]!;
protected string LoginToken => (string)HttpContext.Items["LoginToken"]!;
/// <summary>
/// 验证请求参数
+11 -1
View File
@@ -1,6 +1,9 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using SimApi.Attributes;
using SimApi.Communications;
using SimApi.Helpers;
using static SimApi.Helpers.SimApiError;
namespace SimApi.Controllers;
@@ -15,7 +18,7 @@ public class SimApiCommonController : SimApiBaseController
[ApiExplorerSettings(IgnoreApi = true)]
public void ExceptionHandler(int code)
{
SimApiError.Error(code);
Error(code);
}
@@ -28,4 +31,11 @@ public class SimApiCommonController : SimApiBaseController
{ "App", SimApiUtil.AppVersion }
};
}
/// <summary>
/// 获取已登录用户信息
/// </summary>
/// <returns></returns>
[HttpPost("/user/info"), SimApiAuth, SimApiDoc("认证", "获取已登录用户信息")]
public SimApiLoginItem UserInfo() => LoginInfo;
}
+3 -3
View File
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using SimApi.Communications;
using StackExchange.Redis;
@@ -137,8 +136,9 @@ public class SimApiAuth(IDistributedCache cache, IConnectionMultiplexer redis)
{
var setCacheKey = TokenSetCacheKey.Replace("{userId}", item.Id);
_redisDb.SetRemove(setCacheKey, token);
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.Remove(cacheKey);
}
var cacheKey = TokenCacheKey.Replace("{token}", token);
cache.Remove(cacheKey);
}
}
+14 -9
View File
@@ -8,9 +8,14 @@ using SimApi.Exceptions;
namespace SimApi.Helpers;
public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
public class SimApiHttpClient
{
public string Server { get; init; } = string.Empty;
public required string Server { get; init; }
public required string AppId { get; init; }
public required string AppKey { get; init; }
public bool Debug { get; init; } = false;
public string SignName { get; init; } = "sign";
public string TimestampName { get; init; } = "timestamp";
public string NonceName { get; init; } = "nonce";
@@ -32,11 +37,11 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
(current, signField) => current + $"{signField}={queries?[signField]}&");
if (!string.IsNullOrEmpty(AppIdName))
{
queryUrl += $"{AppIdName}={appId}&";
queryUrl += $"{AppIdName}={AppId}&";
}
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
var signStr = $"{queryUrl}&{appKey}";
var signStr = $"{queryUrl}&{AppKey}";
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
if (queries != null)
@@ -60,12 +65,12 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
url = Server + url;
if (!string.IsNullOrEmpty(AppIdName))
{
url += $"?{AppIdName}={appId}";
url += $"?{AppIdName}={AppId}";
}
var req = new SimApiOneFieldRequest<string>
{
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
};
return Query<T>(url, req);
}
@@ -82,7 +87,7 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
{
var req = new SimApiOneFieldRequest<string>
{
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), AppKey)
};
return SignQuery<T>(url, req, queries);
}
@@ -98,13 +103,13 @@ public class SimApiHttpClient(string? appId, string appKey, bool debug = false)
private T? Query<T>(string url, object? req)
{
var http = new HttpClient();
if (debug)
if (Debug)
{
Console.WriteLine($"[HTTPCLIENT请求] {url}\n{SimApiUtil.Json(req)}\n");
}
var resp = http.PostAsJsonAsync(url, req).Result;
if (debug)
if (Debug)
{
Console.WriteLine($"[HTTPCLIENT响应] {resp.Content.ReadAsStringAsync().Result}\n");
}
+8
View File
@@ -0,0 +1,8 @@
using SimApi.Communications;
namespace SimApi.Interfaces;
public interface ISimApiAuthChecker
{
public void Run(SimApiLoginItem loginItem, string token);
}
+5 -6
View File
@@ -1,4 +1,5 @@
using System.Threading.Tasks;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SimApi.Helpers;
@@ -11,11 +12,9 @@ public class SimApiAuthMiddleware(RequestDelegate next)
{
public Task Invoke(HttpContext httpContext, SimApiAuth auth)
{
string? token = null;
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
{
token = header;
}
var token =
httpContext.Request.Headers["Token"].FirstOrDefault()
?? httpContext.Request.Query["token"].FirstOrDefault();
if (string.IsNullOrEmpty(token)) return next(httpContext);
var login = auth.GetLogin(token);
+24 -18
View File
@@ -18,6 +18,7 @@ using Microsoft.Extensions.Logging;
using SimApi.Attributes;
using SimApi.CoceSdk;
using SimApi.Configurations;
using SimApi.Interfaces;
using SimApi.Logger;
using SimApi.SwaggerFilters;
using StackExchange.Redis;
@@ -63,6 +64,20 @@ public static class SimApiExtensions
builder.AddSingleton<CoceApp>();
}
var simApiAuthChecker = typeof(ISimApiAuthChecker);
var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var callerAssembly = callingMethod?.DeclaringType?.Assembly;
var callerTypes = callerAssembly?.GetTypes() ?? [];
foreach (var type in callerTypes)
{
if (type is { IsClass: true, IsAbstract: false } && simApiAuthChecker.IsAssignableFrom(type))
{
builder.AddScoped(simApiAuthChecker, type);
}
}
if (simApiOptions.EnableJob)
{
builder.AddHangfire(x =>
@@ -96,12 +111,7 @@ public static class SimApiExtensions
if (simApiOptions.EnableSynapse)
{
builder.AddSingleton<Synapse>();
//自动依赖注入
var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var assembly = callingMethod?.DeclaringType?.Assembly;
var types = assembly?.GetTypes() ?? [];
foreach (var type in types)
foreach (var type in callerTypes)
{
var methodsWithSynapse = type.GetMethods()
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
@@ -394,6 +404,14 @@ public static class SimApiExtensions
builder.MapControllers();
}
var checkers = builder.Services.CreateScope().ServiceProvider.GetServices<ISimApiAuthChecker>().ToArray();
if (checkers.Length != 0)
{
var msg = checkers.Aggregate("开始配置SimApiAuthChecker...",
(current, checker) => current + $"\n|- {checker.GetType().FullName}");
logger.LogInformation(msg);
}
if (options.EnableSimApiGateAuth)
{
logger.LogInformation("开始配置SimApiGateAuth...");
@@ -412,18 +430,6 @@ public static class SimApiExtensions
{
logger.LogInformation("开始配置SimApiAuth...");
builder.UseMiddleware<SimApiAuthMiddleware>();
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
defaults: new
{
controller = "SimApiAuth",
action = "UserInfo"
});
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
defaults: new
{
controller = "SimApiAuth",
action = "CheckLogin"
});
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
defaults: new
{