Adding a custom header to the swagger UI for API authentication

If you need to add a custom HTTP header such as x-api-key to your API calls and want to include this while using the swagger API, you can use the code below and add it to your program.cs file in a .NET Core application to get it working.

builder.Services.AddSwaggerGen(c =>
    {
        c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
        {
            Description = "The API Key to access the API",
            Type = SecuritySchemeType.ApiKey,
            Name = "x-api-key",
            In = ParameterLocation.Header,
            Scheme = "ApiKeyScheme"
        });
        var scheme = new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "ApiKey"
            },
            In = ParameterLocation.Header
        };
        var requirement = new OpenApiSecurityRequirement
        {
            {scheme, new List<string>() }
        };
        c.AddSecurityRequirement(requirement);
    });

On the swagger UI, you will then see an Authorize button that when clicked, allows you to enter the header value and it will be included in your requests.

Full code sample on GitHub - https://github.com/cliffordru/ApiKeyAuthentication

Need a developer, architect or manager? I am available - email me at [email protected]

Add comment