33 lines
1.2 KiB
C#
33 lines
1.2 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.OpenApi.Models;
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
|
|
public class SwaggerOperationFilter : IOperationFilter
|
|
{
|
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
|
{
|
|
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
|
|
.Union(context.MethodInfo.GetCustomAttributes(true))
|
|
.OfType<AuthorizeAttribute>();
|
|
|
|
if (authAttributes.Any())
|
|
{
|
|
var securityRequirement = new OpenApiSecurityRequirement()
|
|
{
|
|
{
|
|
new OpenApiSecurityScheme
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type = ReferenceType.SecurityScheme,
|
|
Id = "Bearer"
|
|
}
|
|
},
|
|
Array.Empty<string>()
|
|
}
|
|
};
|
|
operation.Security = new List<OpenApiSecurityRequirement> { securityRequirement };
|
|
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
|
|
}
|
|
}
|
|
} |