0

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
        });
    }
SamulP
  • 205
  • 1
  • 4
  • 12
  • 1
    Would this be of any help? I had this same sort of requirement with some endpoints being open and some being behind auth. https://stackoverflow.com/questions/56234504/migrating-to-swashbuckle-aspnetcore-version-5/60356984#60356984 Endpoints that needed authorize with one policy or the other would be tagged with that schema in the Authorize attribute – Ben Sampica Jul 24 '20 at 22:46
  • @BenSampica Thanks! That helps but I was able to implement multiple authentication in the API, only that I can't get Swagger to work properly when invoking a method(when I tried to invoke an endpoint, I got to provide headers for both API Key and JWT when only one is required). – SamulP Jul 24 '20 at 23:06
  • Can you post your generated openapi spec and config? – Ben Sampica Jul 25 '20 at 02:03
  • @BenSampica I added snippets in my post. – SamulP Jul 27 '20 at 14:24

0 Answers0