I have an API that requires two authentication types: JWT and API Key. Some endpoints require JWT while the rest require API Key. How can I set up Swagger so that the right security requirement is applied? I tried by adding operation parameters through IOperationFilter but that gives me both authentication types where only one is needed. Any hint is greatly appreciated!
Here is what I have in Startup.cs:
services.AddSwaggerGen((Action<SwaggerGenOptions>)(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.OperationFilter<MyTokenFilter>();
c.SwaggerGeneratorOptions.IgnoreObsoleteActions = true;
c.CustomSchemaIds(x => x.FullName);
c.DocInclusionPredicate((docName, apiDesc) => {
if (apiDesc.HttpMethod == null) return false;
return true;
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
}));
And here is what I have in 'MyTokenFilter':
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter()
{
Name = "TokenName1",
In = ParameterLocation.Header,
Required = true
});
operation.Parameters.Add(new OpenApiParameter()
{
Name = "X-API-Key",
In = ParameterLocation.Header,
Required = false
});
}