Falcon.SugarApi/Falcon.SugarApi/FalconClaim/AddFalconClaimHeaderFilter.cs

45 lines
1.7 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;
namespace Falcon.SugarApi.FalconClaim
{
/// <summary>
/// 为swagger openapi接口增加验证选项
/// </summary>
public class AddFalconClaimHeaderFilter:IOperationFilter
{
/// <inheritdoc/>
public void Apply(OpenApiOperation operation,OperationFilterContext context) {
var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
//var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter)
// .Any(filter => filter is FalconClaimAuthorizeAttribute);
var metedata = context.ApiDescription.ActionDescriptor.EndpointMetadata;
var isAuthorized = metedata.Any(m => m is FalconClaimAuthorizeAttribute);
var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter)
.Any(filter => filter is IAllowAnonymousFilter);
if(isAuthorized && !allowAnonymous) {
operation.Parameters = operation.Parameters ?? new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter {
Name = FalconClaimOption.FalconAuthenticationKey,
In = ParameterLocation.Header,
Description = FalconClaimOption.Description,
Required = true,
Schema = new OpenApiSchema {
Type = "string",
Default = new OpenApiString(FalconClaimOption.TokenPrefix),
},
});
}
}
}
}