How To Configure SWAGGER UI with ASP.NET Core 6 Web API

It is recommended that you go with token-based authentication (aka OAuth2.0), if you wish to maintain a secure line between the API and the client. ASP.NET Core Web API needs API Key Authentication for security. In this post we will discuss, Creating a middleware to secure ASP.NET Core Web APIs with API Key Authentication 

Step by Step guide to configure Swagger UI with ASP.NET Core 6:

A method for using API Keys to authenticate an application has been explained in this article as well as to show how to incorporate the Swagger UI for API Key Authentication flow into .NET Core 6.

builder.Services.AddSwaggerGen(c =>
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api Key Auth", Version = "v1" });
    c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
        Description = "ApiKey should be in header",
        Type = SecuritySchemeType.ApiKey,
        Name = "XApiKey",
        In = ParameterLocation.Header,
        Scheme = "ApiKeyScheme"
    var key = new OpenApiSecurityScheme()
        Reference = new OpenApiReference
            Type = ReferenceType.SecurityScheme,
            Id = "ApiKey"
        In = ParameterLocation.Header
    var requirement = new OpenApiSecurityRequirement
                             { key, new List<string>() }

 By initiation of OpenApiSecurityScheme and OpenApiSecurityRequirement classes, we can enable the authentication by calling AddSecurityDefinition and AddSecurityRequirement functions.

Let’s try without the key.

Configure SWAGGER UI with ASP.NET Core

We will get the response 401 from the swagger that shows it’s unauthorized.

No lets authorize the API’s by applying the key. Click on authorize

Configure SWAGGER UI with ASP.NET Core

Submit the key.

Now we will click on authorize and execute any API.

Now we can see the data and the response code which is 200.


So in this topic we have learnt how we can configure the swagger UI in our ASP.NET Core 6 web Application. If you face any issues or have any suggestions. Do not hesitate to ask in the comments below.

Leave a Comment