I am creating an api with .net6.0. I wanted to add Swagger UI for the api document , which I added and it works for the most part. The only problem I am facing is swagger UI is showing padlock on every endpoint there exists.
Below is my code - Program.cs
builder.Services.AddSwaggerGen(options =>
{
options.SupportNonNullableReferenceTypes();
options.OperationFilter<MyApi.API.Filters.SecurityRequirementsOperationFilter>();
options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
options.SwaggerDoc("v1", new OpenApiInfo() { Title = "MyAPI API", Version = "v1" });
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme()
{
Reference=new OpenApiReference()
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
options.IncludeXmlComments(xmlPath);
});
Here as you can see I am using operation filter to mark the authorize options.
安全要求 (我的行动过滤器)
public class SecurityRequirementsOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// Policy names map to scopes
var requiredScopes = context.MethodInfo
.GetCustomAttributes(true)
.OfType<AuthorizeAttribute>()
.Select(attr => attr.Policy)
.Distinct();
if (requiredScopes.Any())
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorised" });
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
operation.Security = new List<OpenApiSecurityRequirement>();
var secReq = new List<OpenApiSecurityRequirement>();
operation.Security.Add(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Description="Adds token to header",
Name="Authorization",
Type=SecuritySchemeType.Http,
In=ParameterLocation.Header,
Scheme = JwtBearerDefaults.AuthenticationScheme,
Reference = new OpenApiReference
{
Type= ReferenceType.SecurityScheme,
Id=JwtBearerDefaults.AuthenticationScheme
}
},new List<string>()
}
});
}
}
}
After these configuration I am doing normal CRUD operations in my controllers which are protected and require the JWT Bearer and hence I have decorated these end point with [Athorize]
attribute,but in addition I also have two endpoints - /login and /register which obviously I want keep them as publicly available so I decorated them with [AllowAnonymus]
attribute.
Problem here is generated swagger UI shows padlock on every endpoint like below -
我如何能够在我公开的终点上清除这些路障? 我在这里没有哪一个组合?
预支