2025-11-01 15:40:55 +08:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
using System.Reflection;
|
2025-12-18 09:08:35 +08:00
|
|
|
|
using Microsoft.OpenApi;
|
2025-11-01 15:40:55 +08:00
|
|
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
|
|
|
|
using SimApi.Attributes;
|
|
|
|
|
|
|
2025-11-02 22:14:34 +08:00
|
|
|
|
namespace SimApi.SwaggerFilters
|
2025-11-01 15:40:55 +08:00
|
|
|
|
{
|
|
|
|
|
|
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;
|
2025-12-18 09:08:35 +08:00
|
|
|
|
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
|
2025-11-01 15:40:55 +08:00
|
|
|
|
{
|
|
|
|
|
|
{
|
2025-12-18 09:08:35 +08:00
|
|
|
|
securitySchemeRef,
|
|
|
|
|
|
[]
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
2025-11-01 15:40:55 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|