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.
Add this inside your Program.cs right beneath your Swagger configuration:
C#
using Microsoft.OpenApi.Models;
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Secured Web API",
Version = "v1",
Description = "API documentation with JWT Bearer Authentication"
});
// 2. Define the Bearer Security Scheme
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter 'Bearer' [space] and then your valid JWT token.\r\n\r\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\""
});
// 3. Add Global Security Requirement so endpoints require authorization by default (optional)
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
var app = builder.Build();
Step 4: Ensure Proper Middleware Ordering
In your HTTP request pipeline, the middleware order is critical. Make sure UseAuthentication() is called before UseAuthorization(), and both appear before your route mappings.
C#
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Secured Web API V1"));
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// 4. Authentication MUST come before Authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllers();
app.Run();
Step 5: Protect Your Controllers and Test in Swagger
Create a sample protected controller to verify that your configuration works as expected. Use the [Authorize] attribute on the controller or specific action methods.
C#
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace YourNamespace.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize] // Locks down the controller
public class SecretDataController : ControllerBase
{
[HttpGet]
public IActionResult GetSecretMessage()
{
return Ok(new { message = "Success! You have accessed a secure endpoint using a valid JWT token." });
}
}
}
How to Test:
Run your application and navigate to
/swagger.You will notice an Authorize button has appeared in the top-right corner of the Swagger UI interface.
Click Authorize, type
Bearerfollowed by your generated JWT token string into the value box, and click Authorize.Expand your
SecretDataendpoint, click Try it out, and hit Execute. Your request will pass through successfully with a200 OKstatus!

Join the conversation! Your thoughts help the community grow.