Adding a Custom Token Header in Swagger for ASP.NET Core

Adding a Custom Token Header in Swagger for ASP.NET Core

When building APIs in ASP.NET Core, it’s common to require clients to pass a token for authentication or other purposes via the headers. If you're using Swagger with Swashbuckle to document your API, you might need to include this custom header (such as an ExecutionToken) in your Swagger UI for testing your APIs.

In this guide, we'll show you how to configure Swagger to accept a custom header (like ExecutionToken) in ASP.NET Core using Swashbuckle.

Step-by-Step: Adding a Custom Header in Swagger

To configure Swagger to include a custom token header in your API requests, follow the steps below:

1. Install Swashbuckle

First, ensure you have the Swashbuckle.AspNetCore NuGet package installed. You can do this by running the following command in your terminal:

bashCopy codedotnet add package Swashbuckle.AspNetCore

Once the package is installed, you're ready to configure Swagger to accept the token header.

2. Configure Swagger to Add the Token Header

Next, you need to modify your Startup.cs (or Program.cs for .NET 6 and later) to configure Swagger to include the token header in all requests.

In Startup.cs (for ASP.NET Core 5 or earlier):

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // Add Swagger
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

            // Add the ExecutionToken as a header parameter in Swagger
            c.AddSecurityDefinition("ExecutionToken", new OpenApiSecurityScheme
            {
                In = ParameterLocation.Header,
                Name = "ExecutionToken",
                Type = SecuritySchemeType.ApiKey,
                Description = "Execution token required for API requests",
                Scheme = "ExecutionTokenScheme"
            });

            // Add security requirement to include the token in all requests
            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "ExecutionToken"
                        }
                    },
                    new string[] { }
                }
            });
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Enable Swagger
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API v1");
        });

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

In Program.cs (for .NET 6 and later):

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Add Swagger
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

    // Add the ExecutionToken as a header parameter in Swagger
    c.AddSecurityDefinition("ExecutionToken", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Name = "ExecutionToken",
        Type = SecuritySchemeType.ApiKey,
        Description = "Execution token required for API requests",
        Scheme = "ExecutionTokenScheme"
    });

    // Add security requirement to include the token in all requests
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "ExecutionToken"
                }
            },
            new string[] { }
        }
    });
});

3. How It Works

  • Security Definition: In the AddSwaggerGen section, the ExecutionToken is added as a security definition. This tells Swagger to include this token in the UI for any endpoints that require it.
  • Security Requirement: By adding a security requirement, you’re enforcing that the token must be provided for all requests made via Swagger.

4. Using the Token in Swagger UI

After configuring Swagger and running your application, navigate to the Swagger UI (typically at /swagger or /swagger/index.html). You'll see an Authorize button at the top of the page.

When you click Authorize, you'll be prompted to enter the ExecutionToken. Once entered, Swagger will automatically include this token in the header for all your API requests, making it easy to test APIs that require token-based authentication.

Now, you’re ready to test your APIs with the ExecutionToken directly from the Swagger UI!