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