๐ 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:
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
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();
๐ค Step 5 โ Create Login Model
Create a folder named Models โ Add class:
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
๐ฎ Step 6 โ Create Auth Controller
Create new controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
public AuthController(IConfiguration config)
{
_config = config;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (model.Username == "admin" && model.Password == "123")
{
var token = GenerateToken(model.Username);
return Ok(new { token });
}
return Unauthorized();
}
private 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(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
๐ Step 7 โ Protect API with [Authorize]
Create a new controller:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[Authorize]
[HttpGet]
public IActionResult Get()
{
return Ok("Access Granted - Secure API");
}
}
๐งช Step 8 โ Test Using Postman
๐น 1. Login API
POST:
https://localhost:port/api/auth/login
Body (JSON):
{
"username": "admin",
"password": "123"
}
โ
Output:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
๐น 2. Access Secure API
GET:
https://localhost:port/api/test
Add Header:
Authorization: Bearer YOUR_TOKEN_HERE
โ
Output:
Access Granted - Secure API
๐ How JWT Works
User logs in
Server verifies credentials
Server generates JWT token
Client stores token
Client sends token in Authorization header
Server validates token
Access granted
๐ Conclusion
In this article, we learned:
JWT Authentication is widely used in modern web development and is an important concept for interviews and real-world applications.