Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5eb7fe081 | ||
|
|
b04a7c86d7 | ||
|
|
8759b593db | ||
|
|
5a46a026a7 | ||
|
|
90124b6e67 | ||
|
|
2499912204 | ||
|
|
dd38f315d5 | ||
|
|
c448381f23 | ||
|
|
8d5b667c88 | ||
|
|
65451d7b80 |
@@ -10,11 +10,11 @@ jobs:
|
|||||||
name: Publish Project to Nuget
|
name: Publish Project to Nuget
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v1
|
- uses: actions/checkout@v4
|
||||||
- name: Setup .NET Core
|
- name: Setup .NET Core
|
||||||
uses: actions/setup-dotnet@v1
|
uses: actions/setup-dotnet@v5
|
||||||
with:
|
with:
|
||||||
dotnet-version: "9.0.305"
|
dotnet-version: "10.x.x"
|
||||||
- name: Publish
|
- name: Publish
|
||||||
run: |
|
run: |
|
||||||
version=`git describe --tags`
|
version=`git describe --tags`
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
using SimApi.ModelBinders;
|
using SimApi.ModelBinders;
|
||||||
|
|
||||||
namespace SimApi.Attributes;
|
namespace SimApi.Attributes;
|
||||||
@@ -8,6 +9,7 @@ namespace SimApi.Attributes;
|
|||||||
public class AesBodyAttribute : ModelBinderAttribute
|
public class AesBodyAttribute : ModelBinderAttribute
|
||||||
{
|
{
|
||||||
public Type KeyProvider { get; set; } = typeof(AesBodyProviderBase);
|
public Type KeyProvider { get; set; } = typeof(AesBodyProviderBase);
|
||||||
|
public override BindingSource BindingSource => BindingSource.Body;
|
||||||
|
|
||||||
public AesBodyAttribute()
|
public AesBodyAttribute()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ namespace SimApi.Attributes;
|
|||||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||||
public class SimApiSignAttribute : ActionFilterAttribute
|
public class SimApiSignAttribute : ActionFilterAttribute
|
||||||
{
|
{
|
||||||
protected Type KeyProvider { get; set; } = typeof(SimApiSignProviderBase);
|
public Type KeyProvider { get; set; } = typeof(SimApiSignProviderBase);
|
||||||
|
|
||||||
public override void OnActionExecuting(ActionExecutingContext context)
|
public override void OnActionExecuting(ActionExecutingContext context)
|
||||||
{
|
{
|
||||||
@@ -101,6 +101,11 @@ public class SimApiSignAttribute : ActionFilterAttribute
|
|||||||
signStr += "&";
|
signStr += "&";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(keyProvider.AppIdName))
|
||||||
|
{
|
||||||
|
signStr += $"{keyProvider.AppIdName}={appId}&";
|
||||||
|
}
|
||||||
|
|
||||||
signStr += $"{keyProvider.TimestampName}={ts}&{keyProvider.NonceName}={nonce}&{key}";
|
signStr += $"{keyProvider.TimestampName}={ts}&{keyProvider.NonceName}={nonce}&{key}";
|
||||||
var sign = context.HttpContext.Request.Query[keyProvider.SignName]
|
var sign = context.HttpContext.Request.Query[keyProvider.SignName]
|
||||||
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.SignName]
|
.FirstOrDefault() ?? context.HttpContext.Request.Headers[keyProvider.SignName]
|
||||||
|
|||||||
@@ -46,23 +46,15 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 动态内容分页
|
/// 分页内容返回
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
public class PageResponse<T>
|
||||||
{
|
{
|
||||||
public T? List { get; set; }
|
public T? List { get; set; }
|
||||||
public int Page { get; set; } = 1;
|
public int Page { get; set; } = 1;
|
||||||
public int Count { get; set; } = 20;
|
public int Count { get; set; } = 20;
|
||||||
public int Total { get; set; }
|
public int Total { get; set; }
|
||||||
|
|
||||||
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
|
|
||||||
{
|
|
||||||
List = list;
|
|
||||||
Page = page;
|
|
||||||
Count = count;
|
|
||||||
Total = total;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ namespace SimApi.Communications;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiLoginItem
|
public class SimApiLoginItem
|
||||||
{
|
{
|
||||||
public string Id { get; set; } = null!;
|
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 object? Extra { get; set; }
|
||||||
|
|||||||
@@ -4,13 +4,30 @@ public class SimApiJobOptions
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// WebUi地址,设置为null表示不启用
|
/// WebUi地址,设置为null表示不启用
|
||||||
|
/// 默认 /jobs
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? DashboardUrl { get; set; } = "/jobs";
|
public string? DashboardUrl { get; set; } = "/jobs";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// webui 用户
|
||||||
|
/// 默认 admin
|
||||||
|
/// </summary>
|
||||||
public string DashboardAuthUser { get; set; } = "admin";
|
public string DashboardAuthUser { get; set; } = "admin";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// webui 密码
|
||||||
|
/// 默认 Admin@123!
|
||||||
|
/// </summary>
|
||||||
public string DashboardAuthPass { get; set; } = "Admin@123!";
|
public string DashboardAuthPass { get; set; } = "Admin@123!";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置为null 使用默认redis配置
|
||||||
|
/// </summary>
|
||||||
public string? RedisConfiguration { get; set; }
|
public string? RedisConfiguration { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置为null 使用默认redis配置
|
||||||
|
/// </summary>
|
||||||
public int? Database { get; set; } = null;
|
public int? Database { get; set; } = null;
|
||||||
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Reflection;
|
|
||||||
using Microsoft.OpenApi.Models;
|
|
||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
||||||
using SimApi.Attributes;
|
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
|
||||||
{
|
|
||||||
public class SimApiAuthOperationFilter : IOperationFilter
|
|
||||||
{
|
|
||||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
|
||||||
{
|
|
||||||
// 检查接口或控制器是否标记了 [SimApiAuth] 特性
|
|
||||||
var requiresAuth =
|
|
||||||
// 方法上有 [SimApiAuth]
|
|
||||||
context.MethodInfo.GetCustomAttributes<SimApiAuthAttribute>(true).Any()
|
|
||||||
||
|
|
||||||
// 控制器上有 [SimApiAuth](继承到所有方法)
|
|
||||||
context.MethodInfo.DeclaringType?.GetCustomAttributes<SimApiAuthAttribute>(true).Any() == true;
|
|
||||||
if (requiresAuth)
|
|
||||||
{
|
|
||||||
// 添加授权要求:关联步骤 2 中定义的 "SimApiAuth" 安全方案
|
|
||||||
operation.Security = new List<OpenApiSecurityRequirement>
|
|
||||||
{
|
|
||||||
new OpenApiSecurityRequirement
|
|
||||||
{
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "SimApiAuth" // 必须与 AddSecurityDefinition 的第一个参数一致
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[] // 无需指定作用域(scope)时留空
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// 未标记 [SimApiAuth] 的接口:不添加安全要求,Swagger 不显示锁图标
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiHttpClient(string? appId, string appKey)
|
||||||
|
{
|
||||||
|
public string Server { get; init; } = string.Empty;
|
||||||
|
public string SignName { get; init; } = "sign";
|
||||||
|
public string TimestampName { get; init; } = "timestamp";
|
||||||
|
public string NonceName { get; init; } = "nonce";
|
||||||
|
public string? AppIdName { get; init; } = "appId";
|
||||||
|
public string[] SignFields { get; init; } = [];
|
||||||
|
|
||||||
|
|
||||||
|
public T? SignQuery<T>(string url, object? body = null, Dictionary<string, string>? queries = null)
|
||||||
|
{
|
||||||
|
url = Server + url;
|
||||||
|
var queryUrl = SignFields.Aggregate(string.Empty,
|
||||||
|
(current, signField) => current + $"{signField}={queries?[signField]}&");
|
||||||
|
if (!string.IsNullOrEmpty(AppIdName))
|
||||||
|
{
|
||||||
|
queryUrl += $"{AppIdName}={appId}&";
|
||||||
|
}
|
||||||
|
|
||||||
|
queryUrl += $"{TimestampName}={(int)SimApiUtil.TimestampNow}&{NonceName}={Guid.NewGuid()}";
|
||||||
|
var signStr = $"{queryUrl}&{appKey}";
|
||||||
|
var path = $"{url}?{queryUrl}&{SignName}={SimApiUtil.Md5(signStr)}";
|
||||||
|
|
||||||
|
if (queries != null)
|
||||||
|
{
|
||||||
|
path = queries.Where(q => !SignFields.Contains(q.Key))
|
||||||
|
.Aggregate(path, (current, q) => current + $"&{q.Key}={q.Value}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Query<T>(path, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? AesQuery<T>(string url, object body)
|
||||||
|
{
|
||||||
|
url = Server + url;
|
||||||
|
if (!string.IsNullOrEmpty(AppIdName))
|
||||||
|
{
|
||||||
|
url += $"?{AppIdName}={appId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
var req = new SimApiOneFieldRequest<string>
|
||||||
|
{
|
||||||
|
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
||||||
|
};
|
||||||
|
return Query<T>(url, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? AesSignQuery<T>(string url, object body, Dictionary<string, string>? queries = null)
|
||||||
|
{
|
||||||
|
var req = new SimApiOneFieldRequest<string>
|
||||||
|
{
|
||||||
|
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
||||||
|
};
|
||||||
|
return SignQuery<T>(url, req, queries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private T? Query<T>(string url, object? req)
|
||||||
|
{
|
||||||
|
var http = new HttpClient();
|
||||||
|
var resp = http.PostAsJsonAsync(url, req).Result;
|
||||||
|
var res = resp.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result;
|
||||||
|
if (res == null)
|
||||||
|
{
|
||||||
|
throw new SimApiException(500, "请求发生错误");
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.Code != 200 ? throw new SimApiException(res.Code, res.Message) : res.Data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ public class SimApiJobWebAuth(string user, string pass) : IDashboardAuthorizatio
|
|||||||
public bool Authorize(DashboardContext context)
|
public bool Authorize(DashboardContext context)
|
||||||
{
|
{
|
||||||
var httpContext = context.GetHttpContext();
|
var httpContext = context.GetHttpContext();
|
||||||
var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault();
|
var authHeader = httpContext.Request.Headers.Authorization.FirstOrDefault();
|
||||||
if (authHeader != null && authHeader.StartsWith("Basic "))
|
if (authHeader != null && authHeader.StartsWith("Basic "))
|
||||||
{
|
{
|
||||||
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
|
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await next(context);
|
await next(context);
|
||||||
|
if (!context.Response.HasStarted)
|
||||||
|
{
|
||||||
switch (context.Response.StatusCode)
|
switch (context.Response.StatusCode)
|
||||||
{
|
{
|
||||||
case 200:
|
case 200:
|
||||||
@@ -36,6 +38,7 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
throw new SimApiException(context.Response.StatusCode);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (SimApiException ex)
|
catch (SimApiException ex)
|
||||||
{
|
{
|
||||||
response = string.IsNullOrEmpty(ex.Message)
|
response = string.IsNullOrEmpty(ex.Message)
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.ModelBinders;
|
namespace SimApi.ModelBinders;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -5,7 +7,7 @@ namespace SimApi.ModelBinders;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class AesBodyProviderBase
|
public abstract class AesBodyProviderBase
|
||||||
{
|
{
|
||||||
public string? AppIdName { get; set; } = "appId";
|
public virtual string? AppIdName { get; set; } = "appId";
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.ModelBinders;
|
namespace SimApi.ModelBinders;
|
||||||
|
|
||||||
public abstract class SimApiSignProviderBase
|
public abstract class SimApiSignProviderBase
|
||||||
@@ -5,34 +7,34 @@ public abstract class SimApiSignProviderBase
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// appId字段的名称
|
/// appId字段的名称
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? AppIdName { get; set; } = "appId";
|
public virtual string? AppIdName { get; set; } = "appId";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 时间戳的字段名
|
/// 时间戳的字段名
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string TimestampName { get; set; } = "timestamp";
|
public virtual string TimestampName { get; set; } = "timestamp";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 随机字符串的字段名
|
/// 随机字符串的字段名
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string NonceName { get; set; } = "nonce";
|
public virtual string NonceName { get; set; } = "nonce";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 签名的字段名
|
/// 签名的字段名
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string SignName { get; set; } = "sign";
|
public virtual string SignName { get; set; } = "sign";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 请求过期时间, 如果为0, 不校验timestamp
|
/// 请求过期时间, 如果为0, 不校验timestamp
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int QueryExpires { get; set; } = 5;
|
public virtual int QueryExpires { get; set; } = 5;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 如果开启,必须配置redis, 每次请求将会缓存nonce
|
/// 如果开启,必须配置redis, 每次请求将会缓存nonce
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool DuplicateRequestProtection { get; set; } = true;
|
public virtual bool DuplicateRequestProtection { get; set; } = true;
|
||||||
|
|
||||||
public string[] SignFields { get; set; } = ["appId"];
|
public virtual string[] SignFields { get; set; } = [];
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 根据appId获取对应的密钥
|
/// 根据appId获取对应的密钥
|
||||||
|
|||||||
+6
-6
@@ -9,7 +9,7 @@
|
|||||||
<Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description>
|
<Description>AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库</Description>
|
||||||
<PackageId>Simcu.SimApi</PackageId>
|
<PackageId>Simcu.SimApi</PackageId>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
|
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -17,14 +17,14 @@
|
|||||||
<Folder Include="Exceptions\"/>
|
<Folder Include="Exceptions\"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.21" />
|
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.22" />
|
||||||
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
<PackageReference Include="Hangfire.Console" Version="1.4.3"/>
|
||||||
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0"/>
|
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0"/>
|
||||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.1" />
|
||||||
<PackageReference Include="Minio" Version="6.0.5" />
|
<PackageReference Include="Minio" Version="7.0.0" />
|
||||||
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
|
<PackageReference Include="MQTTnet" Version="5.0.1.1416"/>
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.6" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.0.1" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.6" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.0.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
|
|||||||
+6
-3
@@ -9,7 +9,7 @@ using Hangfire.Redis.StackExchange;
|
|||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi;
|
||||||
using SimApi.Middlewares;
|
using SimApi.Middlewares;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -19,6 +19,7 @@ using SimApi.Attributes;
|
|||||||
using SimApi.CoceSdk;
|
using SimApi.CoceSdk;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
|
using SimApi.SwaggerFilters;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
@@ -123,7 +124,10 @@ public static class SimApiExtensions
|
|||||||
}
|
}
|
||||||
|
|
||||||
x.CustomSchemaIds(type => type.FullName?.Replace("+", "."));
|
x.CustomSchemaIds(type => type.FullName?.Replace("+", "."));
|
||||||
x.OperationFilter<SimApiResponseSchemaFilter>();
|
x.OperationFilter<SimApiResponseOperationFilter>();
|
||||||
|
x.OperationFilter<SimApiSignOperationFilter>();
|
||||||
|
x.OperationFilter<AesBodyOperationFilter>();
|
||||||
|
x.SchemaFilter<GlobalDynamicObjectSchemaFilter>();
|
||||||
if (simApiOptions.EnableSimApiAuth)
|
if (simApiOptions.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
x.OperationFilter<SimApiAuthOperationFilter>();
|
x.OperationFilter<SimApiAuthOperationFilter>();
|
||||||
@@ -236,7 +240,6 @@ public static class SimApiExtensions
|
|||||||
if (simApiOptions.EnableSimApiResponseFilter)
|
if (simApiOptions.EnableSimApiResponseFilter)
|
||||||
{
|
{
|
||||||
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
|
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
|
||||||
.AddXmlSerializerFormatters()
|
|
||||||
.AddJsonOptions(opt =>
|
.AddJsonOptions(opt =>
|
||||||
{
|
{
|
||||||
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 自定义 Swagger 过滤器:将标注 [AesBody] 的参数显示在 Request Body 中
|
||||||
|
/// </summary>
|
||||||
|
public class AesBodyOperationFilter : IOperationFilter
|
||||||
|
{
|
||||||
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
|
{
|
||||||
|
foreach (var parameter in context.ApiDescription.ParameterDescriptions)
|
||||||
|
{
|
||||||
|
var hasAesBodyAttr = parameter.ParameterInfo()
|
||||||
|
.GetCustomAttribute<AesBodyAttribute>() != null;
|
||||||
|
if (!hasAesBodyAttr) continue;
|
||||||
|
// 1. 移除默认的 Query 参数描述(如果存在)
|
||||||
|
var queryParam = operation.Parameters
|
||||||
|
.FirstOrDefault(p => p.Name == parameter.Name);
|
||||||
|
if (queryParam != null)
|
||||||
|
{
|
||||||
|
operation.Parameters.Remove(queryParam);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 添加 Body 参数描述
|
||||||
|
// 获取参数类型的 Schema(Swagger 模型定义)
|
||||||
|
var schema = context.SchemaGenerator.GenerateSchema(
|
||||||
|
parameter.Type,
|
||||||
|
context.SchemaRepository);
|
||||||
|
|
||||||
|
// 将参数添加到 Request Body
|
||||||
|
operation.RequestBody = new OpenApiRequestBody
|
||||||
|
{
|
||||||
|
Content = new Dictionary<string, OpenApiMediaType>
|
||||||
|
{
|
||||||
|
{
|
||||||
|
"application/json", // 假设使用 JSON 格式
|
||||||
|
new OpenApiMediaType { Schema = schema }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Description = "内容为加密前内容,需要转换为JSON后使用AES加密后提交,提交格式为 {\"data\":\"AES密文\"}",
|
||||||
|
Required = true // 标记为必填
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
|
public class GlobalDynamicObjectSchemaFilter : ISchemaFilter
|
||||||
|
{
|
||||||
|
public void Apply(IOpenApiSchema schema, SchemaFilterContext context)
|
||||||
|
{
|
||||||
|
if (!IsDynamicObjectType(context.Type)) return;
|
||||||
|
var oaSchema = schema as OpenApiSchema;
|
||||||
|
oaSchema.AdditionalPropertiesAllowed = true;
|
||||||
|
oaSchema.AdditionalProperties = new OpenApiSchema
|
||||||
|
{
|
||||||
|
Type = JsonSchemaType.Object, // 表示 value 可以是任意类型(兼容所有类型)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. 覆盖默认示例,使用包含多种类型的示例
|
||||||
|
oaSchema.Example = CreateMultiTypeExample();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 判断是否为需要处理的“动态对象”类型
|
||||||
|
private bool IsDynamicObjectType(Type? type)
|
||||||
|
{
|
||||||
|
if (type == null) return false;
|
||||||
|
if (typeof(IDictionary).IsAssignableFrom(type) ||
|
||||||
|
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == typeof(object))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return type.Name.Contains("AnonymousType") && type.Namespace == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建包含多种类型的示例(覆盖默认的 string 示例)
|
||||||
|
private JsonNode CreateMultiTypeExample()
|
||||||
|
{
|
||||||
|
return new JsonObject
|
||||||
|
{
|
||||||
|
// 字符串类型:JsonValue.Create 包装字符串
|
||||||
|
["stringProp"] = JsonValue.Create("example string"),
|
||||||
|
// 数字类型:支持 int/long/double 等,JsonValue 自动适配
|
||||||
|
["numberProp"] = JsonValue.Create(123),
|
||||||
|
// 布尔类型
|
||||||
|
["boolProp"] = JsonValue.Create(true),
|
||||||
|
// 嵌套对象:JsonObject 对应 OpenApiObject
|
||||||
|
["objectProp"] = new JsonObject
|
||||||
|
{
|
||||||
|
["nestedKey"] = JsonValue.Create("nested value")
|
||||||
|
},
|
||||||
|
// 数组类型:JsonArray 对应 OpenApiArray
|
||||||
|
["arrayProp"] = new JsonArray
|
||||||
|
{
|
||||||
|
JsonValue.Create(1), // 数组内数字
|
||||||
|
JsonValue.Create("two") // 数组内字符串
|
||||||
|
},
|
||||||
|
// 可选:添加 null 值示例(若需要)
|
||||||
|
["nullProp"] = null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters
|
||||||
|
{
|
||||||
|
public class SimApiAuthOperationFilter : IOperationFilter
|
||||||
|
{
|
||||||
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
|
{
|
||||||
|
// 检查接口或控制器是否标记了 [SimApiAuth] 特性
|
||||||
|
var requiresAuth =
|
||||||
|
// 方法上有 [SimApiAuth]
|
||||||
|
context.MethodInfo.GetCustomAttributes<SimApiAuthAttribute>(true).Any()
|
||||||
|
||
|
||||||
|
// 控制器上有 [SimApiAuth](继承到所有方法)
|
||||||
|
context.MethodInfo.DeclaringType?.GetCustomAttributes<SimApiAuthAttribute>(true).Any() == true;
|
||||||
|
if (!requiresAuth) return;
|
||||||
|
|
||||||
|
// 关键修复:正确构造 OpenApiSecuritySchemeReference(匹配键类型要求)
|
||||||
|
var securitySchemeRef = new OpenApiSecuritySchemeReference(
|
||||||
|
referenceId: "SimApiAuth", // 必须与 AddSecurityDefinition 的 ID 一致
|
||||||
|
hostDocument: null,
|
||||||
|
externalResource: null
|
||||||
|
);
|
||||||
|
|
||||||
|
// 给 Security 赋值(确保键类型是 OpenApiSecuritySchemeReference)
|
||||||
|
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||||
|
operation.Security.Add(new OpenApiSecurityRequirement
|
||||||
|
{
|
||||||
|
{
|
||||||
|
securitySchemeRef,
|
||||||
|
[]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi;
|
||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -9,9 +9,9 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
|
||||||
namespace SimApi.Helpers;
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
public class SimApiResponseSchemaFilter : IOperationFilter
|
public class SimApiResponseOperationFilter : IOperationFilter
|
||||||
{
|
{
|
||||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.OpenApi;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.ModelBinders;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
|
public class SimApiSignOperationFilter(IServiceProvider serviceProvider) : IOperationFilter
|
||||||
|
{
|
||||||
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||||
|
{
|
||||||
|
// 1. 检查当前方法或类是否标注了 SimApiSignAttribute 及其子类
|
||||||
|
var signAttribute = context.MethodInfo.GetCustomAttribute<SimApiSignAttribute>(inherit: true)
|
||||||
|
?? context.MethodInfo.DeclaringType?.GetCustomAttribute<SimApiSignAttribute>(inherit: true);
|
||||||
|
|
||||||
|
if (signAttribute == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyProviderType = signAttribute.KeyProvider;
|
||||||
|
if (!typeof(SimApiSignProviderBase).IsAssignableFrom(keyProviderType))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"KeyProvider 必须继承自 {nameof(SimApiSignProviderBase)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
SimApiSignProviderBase? keyProvider;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
keyProvider =
|
||||||
|
serviceProvider.CreateScope().ServiceProvider.GetService(keyProviderType) as SimApiSignProviderBase;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"无法从 DI 容器获取 {keyProviderType.Name} 实例:{ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keyProvider == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"{keyProviderType.Name} 未在 DI 容器中注册");
|
||||||
|
}
|
||||||
|
|
||||||
|
var signStr = keyProvider.SignFields.Aggregate(string.Empty, (current, field) => current + $"{field}=xxx&");
|
||||||
|
if (!string.IsNullOrEmpty(keyProvider.AppIdName))
|
||||||
|
{
|
||||||
|
signStr += $"{keyProvider.AppIdName}=xxx&";
|
||||||
|
}
|
||||||
|
|
||||||
|
signStr += $"{keyProvider.TimestampName}=xxx&{keyProvider.NonceName}=xxx&签名密钥";
|
||||||
|
|
||||||
|
var signParameters = new List<(string Name, string Description, bool Required)>
|
||||||
|
{
|
||||||
|
(keyProvider.TimestampName, "时间戳(秒级)", true),
|
||||||
|
(keyProvider.NonceName, "随机字符串", true),
|
||||||
|
(keyProvider.SignName, $"MD5签名结果,签名MD5字符串: {signStr}", true)
|
||||||
|
};
|
||||||
|
if (keyProvider.AppIdName != null)
|
||||||
|
{
|
||||||
|
signParameters.Add((keyProvider.AppIdName, "应用标识", true));
|
||||||
|
}
|
||||||
|
|
||||||
|
signParameters.AddRange(keyProvider.SignFields.Where(x => x != keyProvider.AppIdName)
|
||||||
|
.Select(f => (f, string.Empty, true)));
|
||||||
|
|
||||||
|
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||||
|
|
||||||
|
foreach (var (name, description, required) in signParameters)
|
||||||
|
{
|
||||||
|
if (operation.Parameters?.Any(p => p.Name == name) == true)
|
||||||
|
{
|
||||||
|
var tmp = operation.Parameters?.FirstOrDefault(p => p.Name == name);
|
||||||
|
if (tmp is OpenApiParameter concreteParam)
|
||||||
|
{
|
||||||
|
// 重新赋值只读属性(通过实例化新对象覆盖,或直接修改具体类的可写属性)
|
||||||
|
concreteParam.Required = required; // OpenApiParameter 的 Required 有 setter
|
||||||
|
concreteParam.Description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
operation.Parameters ??= new List<IOpenApiParameter>();
|
||||||
|
operation.Parameters.Add(new OpenApiParameter
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
In = ParameterLocation.Query, // 指定为 Query 参数
|
||||||
|
Description = description,
|
||||||
|
Required = required,
|
||||||
|
Schema = new OpenApiSchema
|
||||||
|
{
|
||||||
|
Type = JsonSchemaType.String // 签名相关参数通常为字符串类型
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user