📌 Introduction
Security is one of the most important parts of modern web applications.
When building APIs using ASP.NET Core, we need a secure way to authenticate users.
One of the most popular methods is:
✅ JWT (JSON Web Token) Authentication
In this article, you will learn:
What is JWT?
Why we use JWT?
How JWT works
Step-by-step implementation in ASP.NET Core
How to test using Postman
Output example
This guide is written in simple language for beginners.
🧠 What is JWT?
JWT stands for:
JWT (JSON Web Token)
It is a secure way to transmit information between client and server as a JSON object.
JWT contains 3 parts:
Header.Payload.Signature
Example Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
🎯 Why Use JWT?
✔ Stateless authentication
✔ Secure API access
✔ Used in modern web & mobile apps
✔ No need to store session on server
✔ Fast and scalable
🛠 Step 1 – Create ASP.NET Core Web API Project
Open Visual Studio
Click Create New Project
Select ASP.NET Core Web API
Choose .NET 8
Project Name:
JWTAuthDemo
Click Create.
📦 Step 2 – Install Required Package
Open NuGet Package Manager and install:
Microsoft.AspNetCore.Authentication.JwtBearer
⚙ Step 3 – Add JWT Settings in appsettings.json
Open:
appsettings.json
Add:
"Jwt": {
"Key": "ThisIsMySecretKey123456",
"Issuer": "JWTAuthDemo",
"Audience": "JWTAuthDemoUsers"
}
🔧 Step 4 – Configure JWT in Program.cs
Open Program.cs and add:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]);
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(key)
};
});
builder.Services.AddControllers();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Join the conversation! Your thoughts help the community grow.