Introduction
JWT (JSON Web Token) authentication is one of the most popular and secure ways to protect APIs in ASP.NET Core. It allows you to build scalable, stateless authentication systems where the server does not need to store session data.
In this guide, you will learn how to implement JWT authentication in ASP.NET Core step by step using simple language, real examples, and best practices. This article is useful for beginners as well as developers building secure web APIs.
What is JWT Authentication?
JWT (JSON Web Token) is a compact, URL-safe token that is used to securely transmit information between client and server.
A JWT token contains three parts:
Header → Contains algorithm and token type
Payload → Contains user data (claims)
Signature → Used to verify the token
Example structure:
Header.Payload.Signature
JWT is widely used in ASP.NET Core Web API authentication because:
It is stateless (no server storage required)
It is secure (signed tokens)
It works well with mobile and SPA applications
Prerequisites
Before implementing JWT authentication in ASP.NET Core, make sure you have:
.NET SDK installed
Basic knowledge of ASP.NET Core Web API
Visual Studio or VS Code
Step 1: Create ASP.NET Core Web API Project
Create a new ASP.NET Core Web API project using CLI:
dotnet new webapi -n JwtAuthDemo
cd JwtAuthDemo
Or use Visual Studio:
Select "ASP.NET Core Web API"
Choose .NET version
Create project
Step 2: Install Required NuGet Packages
Install JWT authentication package:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
This package helps validate and handle JWT tokens.
Step 3: Add JWT Settings in appsettings.json
Add configuration for JWT:
"Jwt": {
"Key": "ThisIsASecretKeyForJwtToken12345",
"Issuer": "YourApp",
"Audience": "YourAppUsers",
"DurationInMinutes": 60
}
Explanation:
Key → Secret key used for signing token
Issuer → Who generates token
Audience → Who uses token
Duration → Token expiry time
Step 4: Create JWT Service
Create a service to generate tokens.
Create folder: Services
Create file: JwtService.cs
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtService
{
private readonly IConfiguration _config;
public JwtService(IConfiguration config)
{
_config = config;
}
public string GenerateToken(string username)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:DurationInMinutes"])),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Join the conversation! Your thoughts help the community grow.