Introduction
JWT (JSON Web Token) authentication is one of the most popular and secure ways to protect APIs in ASP.NET Core. It is widely used in modern web applications, mobile apps, and microservices because it is stateless, scalable, and easy to integrate.
In simple words, JWT authentication allows users to log in once and then use a token to access protected resources without sending credentials again and again.
In this article, we will learn how to implement JWT authentication in ASP.NET Core step by step, using simple language, real examples, and best practices.
What is JWT (JSON Web Token)?
A JSON Web Token (JWT) is a compact and secure way to transmit information between parties as a JSON object.
A JWT consists of three parts:
Header → Contains algorithm and token type
Payload → Contains user data (claims)
Signature → Used to verify the token
Example format:
Header.Payload.Signature
Why Use JWT Authentication?
Stateless authentication (no server session required)
Scalable for large applications
Works well with APIs and microservices
Secure when implemented correctly
Step-by-Step Implementation of JWT Authentication in ASP.NET Core
Step 1: Create ASP.NET Core Web API Project
Create a new Web API project using Visual Studio or .NET CLI.
Step 2: Install Required NuGet Packages
Install the following package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Step 3: Add JWT Settings in appsettings.json
"Jwt": {
"Key": "ThisIsASecretKeyForJWT",
"Issuer": "YourApp",
"Audience": "YourAppUsers",
"DurationInMinutes": 60
}
Step 4: Configure JWT Authentication in Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var jwtSettings = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]);
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 = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Join the conversation! Your thoughts help the community grow.