fix swagger, add simapihttpclient
This commit is contained in:
@@ -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]
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiHttpClient(string? appId, string appKey)
|
||||||
|
{
|
||||||
|
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, Dictionary<string, string>? queries = null)
|
||||||
|
{
|
||||||
|
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}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var http = new HttpClient();
|
||||||
|
var resp = http.PostAsJsonAsync(path, body).Result;
|
||||||
|
return resp.Content.ReadFromJsonAsync<T>().Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? AesQuery<T>(string url, object body)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(AppIdName))
|
||||||
|
{
|
||||||
|
url += $"?{AppIdName}={appId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
var req = new SimApiOneFieldRequest<string>
|
||||||
|
{
|
||||||
|
Data = SimApiAesUtil.Encrypt(SimApiUtil.Json(body), appKey)
|
||||||
|
};
|
||||||
|
var http = new HttpClient();
|
||||||
|
var resp = http.PostAsJsonAsync(url, req).Result;
|
||||||
|
return resp.Content.ReadFromJsonAsync<T>().Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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获取对应的密钥
|
||||||
|
|||||||
+4
-1
@@ -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,9 @@ 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>();
|
||||||
if (simApiOptions.EnableSimApiAuth)
|
if (simApiOptions.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
x.OperationFilter<SimApiAuthOperationFilter>();
|
x.OperationFilter<SimApiAuthOperationFilter>();
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
|
||||||
|
namespace SimApi.SwaggerFilters;
|
||||||
|
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
|
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 // 标记为必填
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
@@ -6,7 +5,7 @@ using Microsoft.OpenApi.Models;
|
|||||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.SwaggerFilters
|
||||||
{
|
{
|
||||||
public class SimApiAuthOperationFilter : IOperationFilter
|
public class SimApiAuthOperationFilter : IOperationFilter
|
||||||
{
|
{
|
||||||
+2
-2
@@ -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,97 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
|
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)));
|
||||||
|
|
||||||
|
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 != null)
|
||||||
|
{
|
||||||
|
tmp.Required = required;
|
||||||
|
tmp.Description = description;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
operation.Parameters ??= new List<OpenApiParameter>();
|
||||||
|
operation.Parameters.Add(new OpenApiParameter
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
In = ParameterLocation.Query, // 指定为 Query 参数
|
||||||
|
Description = description,
|
||||||
|
Required = required,
|
||||||
|
Schema = new OpenApiSchema
|
||||||
|
{
|
||||||
|
Type = "string" // 签名相关参数通常为字符串类型
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user