Enable JWT in Swagger for .NET APIs – Step-by-Step Guide

Waleed NaveedWaleed Naveed
4 min read

When building secure APIs in .NET, JWT (JSON Web Token) is one of the most popular choices for implementing authorization after authentication. It allows the server to authorize requests without storing session data, making it perfect for stateless APIs.

However, when working with secure endpoints locally, developers often find it tricky to test them through Swagger UI, because Swagger doesn’t support JWT authentication by default. This guide will show you how to enable JWT token support in Swagger for .NET APIs, so you can test secure endpoints directly from your browser.

What You'll Learn

  • Why Swagger needs a custom configuration for JWT

  • How to integrate JWT authentication into Swagger

  • How to test your secured endpoints from the browser

Quick Project Overview

For this demo, we're using the same .NET 8 Web API project from our previous blog on K6 Load Testing. The complete source code is available on GitHub.

This API includes the following endpoints:

  • GET /api/Product/public – a public endpoint accessible to anyone

  • GET /api/Product/secure?id={id} – a secure endpoint that requires a valid JWT

  • POST /api/Auth/login – returns a JWT token for a valid user

We're using an in-memory database seeded with one user and a few sample products to keep the setup simple — no external DB or hosting required.

Why Swagger Doesn’t Support JWT by Default

Swagger UI is great for testing public APIs, but it doesn’t support JWT authentication out of the box. When you try calling a secure endpoint, it won’t include an Authorization header unless you explicitly configure it.

Here’s why:

  • Swagger doesn’t assume what kind of authentication your API uses — it stays generic by default.

  • JWT requires user input (a token), which means Swagger needs some UI customization to accept and send it.

  • To support this, you need to manually define JWT as a security scheme and configure it in your Swagger setup.

That’s why a bit of configuration is needed — to enable interactive testing of secure endpoints right inside Swagger UI, without switching to tools like Postman.

The Problem

By default, Swagger UI doesn’t prompt you for a token or include any authorization headers in requests. This leads to:

  • Any call to secure endpoints failing with a 401 Unauthorized

  • Needing to test via Postman or another external tool

Here’s an example from our project, where we try to access the /api/Product/secure?id=1 endpoint without providing a JWT:

As expected, we receive a 401 Unauthorized response since the JWT token wasn't provided.

But the good news? We can fix this with a few simple lines of configuration.

Configuring Swagger for JWT Authentication

Now that we understand the problem, let’s walk through how to enable JWT authentication in Swagger so you can test secure endpoints directly from the browser during development.

1. Add a Swagger Configuration Extension

First, we’ll extract the JWT configuration into a reusable extension method. Create a new file named SwaggerServiceExtensions.cs and add the following code:

public static class SwaggerServiceExtensions
{
    public static IServiceCollection AddSwaggerWithJwtAuth(this IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "K6LoadTestDemo API", Version = "v1" });

            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Name = "Authorization",
                Type = SecuritySchemeType.Http,
                Scheme = "Bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Description = "Enter your Bearer token",
            });

            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });
        });

        return services;
    }
}

This tells Swagger how to interpret JWT as a bearer token and adds the "Authorize" button in the UI.

2. Register It in Program.cs

Next, go to your Program.cs file and register the extension method. You’ll also ensure the Swagger UI is enabled:

builder.Services.AddSwaggerWithJwtAuth();

// Enable Swagger middleware
app.UseSwagger();
app.UseSwaggerUI();

That’s it — the configuration is done.

Testing Secure Endpoints in Swagger

Now, let’s test it out using our sample API project.

When we run the API (dotnet run) and navigate to https://localhost:7061/swagger, we should see an "Authorize" button at the top-right:

Click it, and a popup will appear asking for a token.

How to Get a JWT Token (In This Project)

To obtain a token, call the login endpoint with a dummy user seeded into the in-memory database.

POST /api/Auth/login

{
  "username": "admin@example.com",
  "password": "123456"
}

First, navigate to the /api/Auth/login endpoint in Swagger, enter the dummy user credentials, and execute the request. You’ll receive a JWT token in the response body. Copy it. Then click the 'Authorize' button again and paste the token.

Click on “Authorize“ button.

Now, try calling the secured end-point /api/Product/secure?id=1 again. This time we should get 200 ok response instead of 401 Unauthorized

Conclusion

Adding JWT authentication to Swagger drastically improves the developer experience. It eliminates the need to switch between Swagger and tools like Postman during development, allowing for faster, smoother testing of secure APIs — which saves time and ensures a smoother dev workflow.

0
Subscribe to my newsletter

Read articles from Waleed Naveed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Waleed Naveed
Waleed Naveed