Explaining ASP.NET Web API JWT Auth Support in Swagger Step-by-Step
Introduction
ASP.NET Web API is a powerful framework to develop HTTP-based services that can be accessed by a wide range of clients, such as browsers, mobile devices, and other traditional clients. JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. Swagger is an open-source framework for generating, describing, calling, and visualizing RESTful web services. Integrating JWT authentication with Swagger in an ASP.NET Web API project makes it easier to document and test your API endpoints.
In this detailed guide, we will cover the step-by-step process to add JWT-based authentication support to Swagger in an ASP.NET Web API project. We will also explain the configuration and code that you will need to understand and implement.
Prerequisites
Before you proceed, ensure you have the following tools and environment:
- Visual Studio 2022 or later: This is the Integrated Development Environment (IDE) used to develop ASP.NET Web API projects. You can download it from the Microsoft website.
- .NET SDK 6.0 or later: This contains the libraries and runtime required to build and run .NET applications.
- Basic understanding of ASP.NET Web API: Familiarity with the structure and components of an ASP.NET Web API project is beneficial.
- Basic understanding of JWT: Knowledge of how JWTs are issued, validated, and used in authentication and authorization is helpful.
Step 1: Create an ASP.NET Web API Project
First, we'll create a new ASP.NET Web API project. Open Visual Studio and follow these steps:
- Go to File > New > Project.
- In the "Create a new project" window, search for "ASP.NET Core Web API".
- Click on "ASP.NET Core Web API" and click "Next".
- Name your project, for example, "JWTAuthSwaggerAPI".
- Choose a storage location and click "Next".
- In the "Additional information" window, ensure .NET 6.0 or later is selected and the project template is "Web API".
- Uncheck the "Enable OpenAPI support" option for this guide because we will manually integrate Swagger with JWT.
- Click "Create".
Visual Studio will generate a new ASP.NET Web API project for you.
Step 2: Install Required NuGet Packages
To implement JWT authentication and integrate Swagger, we need some NuGet packages:
- Microsoft.AspNetCore.Authentication.JwtBearer: This package provides the necessary middleware to authenticate using JWTs.
Open the NuGet Package Manager Console in Visual Studio (Tools -> NuGet Package Manager -> Package Manager Console) and run the following command:
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Install-Package Swashbuckle.AspNetCore
Alternatively, you can install these packages using the NuGet Package Manager UI.
Step 3: Configure JWT Authentication
Now, we need to configure JWT authentication in the Program.cs
(or Startup.cs
in older versions) file.
- Create a JWT Authentication Scheme:
Update your
Program.cs
file to include JWT authentication configuration:
using Microsoft.OpenApi.Models;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWTAuthSwaggerAPI", Version = "v1" });
// Add JWT authentication support to Swagger
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
// JWT Authentication configuration
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:ValidAudience"],
ValidIssuer = builder.Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Secret"]))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
- Configure JWT Settings in
appsettings.json
: Add JWT settings to yourappsettings.json
file:
{
"JWT": {
"ValidAudience": "Audience",
"ValidIssuer": "Issuer",
"Secret": "ThisIsASecretKeyForJWTTokenGenerationAndValidation"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Step 4: Implement JWT Token Generation
We need to implement a controller to generate JWT tokens. Create a new controller called AuthController
:
Create the
AuthController
: Right-click on theControllers
folder in your project, select Add > Controller. Choose API Controller - Empty and name itAuthController
.Implement JWT Token Issuance Logic:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
// Validate the user credentials (for example, against a database).
// For demonstration, we are assuming valid credentials.
if (login.Username == "user" && login.Password == "password")
{
// Create the security token descriptor
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, login.Username),
new Claim(ClaimTypes.Role, "User")
}),
Expires = DateTime.UtcNow.AddMinutes(20),
Issuer = _configuration["JWT:ValidIssuer"],
Audience = _configuration["JWT:ValidAudience"],
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
return Ok(new { token = jwtToken });
}
return Unauthorized();
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
Step 5: Test the JWT Authentication and Swagger Integration
Run your project using F5 or the "Run" button in Visual Studio. The application will start, and you can access Swagger UI at https://localhost:<port>/swagger
.
Obtain a JWT Token: Use the Swagger UI to call the
/api/auth/login
endpoint. Provide the username and password, and you should receive a JWT token in the response.Authenticate using the JWT Token in Swagger UI: In Swagger UI, click on the "Authorize" button on the top right side. Enter
Bearer <your_jwt_token>
and click "Authorize".Test Authenticated API Endpoints: Now, any API endpoint that requires authentication should allow requests that include the JWT token in the Authorization header. For example, create a protected controller with the
[Authorize]
attribute:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class ValuesController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new { message = "This is a protected endpoint." });
}
}
When you try to access /api/values
in Swagger UI, it should work only if the request is authenticated with the JWT token.
Conclusion
In this guide, you learned how to integrate JWT authentication into an ASP.NET Web API project and enable JWT support in Swagger. This setup is essential for securing your API and ensuring that Swagger UI can be used to test your protected endpoints. By following the steps, you should have a working sample that demonstrates JWT authentication in an ASP.NET Web API and its integration with Swagger UI.
Remember, the example in this guide uses hard-coded credentials, which is not secure for production environments. For actual applications, you should validate user credentials against a secure database and follow best practices for generating and protecting JWT tokens.