Swagger UI for API Key Authentication Flow with .NET Core 6


API key authentication will keep a secure line between the API and clients, however, if you wish to have user authentication, go with token-based authentication, aka OAuth2.0. In this article, you will learn how to implement the API Key Authentication to secure the ASP.NET Core Web API by creating a middleware. 

Swagger UI for API Key Authentication flow :

This article I have explained how to develop the application with API Key Authentication.

In this article I’m going to explain how to integrate the Swagger UI for API Key Authentication flow with .NET Core 6.

Open Program.cs, add following code

builder.Services.AddSwaggerGen(c =>
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api Key Auth", Version = "v1" });
    c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
        Description = "ApiKey must appear 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>() }

 To enable the authentication, we need call AddSecurityDefinition and AddSecurityRequirement functions by initiating OpenApiSecurityScheme and OpenApiSecurityRequirement classes respectively.

Without applying the key.

Swagger without API Key

Swagger will return 401 unauthorize.

Click on Authorize button to configure the key.

Add Key

Add API Key

Click on Authorize and execute the API.

Swagger with API Key

WeatherForecast API returns the response with expected payload.

Download source code in this Github repository.

Happy Coding!!!


Leave a Reply