When building modern APIs, securing your endpoints with JSON Web Tokens (JWT) is an industry standard. However, once you lock down your controllers with the [Authorize] attribute, testing them can become cumbersome if your API documentation tool doesn't know how to handle credentials.
Fortunately, you can configure Swashbuckle. AspNetCore to display an Authorize button directly inside your Swagger UI. This allows you to generate a token, plug it right into the browser interface, and test both public and protected endpoints seamlessly.
In this comprehensive guide, we will walk through setting up JWT Bearer authentication and integrating it into your Swagger UI in an ASP.NET Core project.
Step 1: Install Required NuGet Packages
To handle JWT token validation, you need the standard authentication bearer package. Ensure you have the following package installed in your project:
Bash
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
(Swashbuckle should already be installed if you followed previous steps to set up Swagger).
Step 2: Configure JWT Authentication Services in Program.cs
First, you need to configure authentication services in your Dependency Injection container. You must define your validation parameters—such as validating the issuer, audience, lifetime, and signing key using your application configuration secrets.
Update your Program.cs file:
C#
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add controllers and views
builder.Services.AddControllersWithViews();
builder.Services.AddEndpointsApiExplorer();
// 1. Configure JWT Authentication
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
builder.Services.AddAuthorization();
Step 3: Configure Swagger Security Definition
Next, configure the Swagger generator (AddSwaggerGen) to recognize the Bearer token scheme. This tells Swagger UI to present an input box for your token when users click the Authorize button.
Jasen FiciPosted Oct 15, 2026, 11:24 AM
Featured in DotNetNews here, thanks for writing it: https://dotnetnews.beehiiv.com/p/new-post-b48f