π JWT (JSON Web Token) Explained: Secure Your APIs the Modern Way
If you're building APIs or modern web apps,
you've probably heard of JWT. But what is it, really?
In this post, we'll break down:
- What JWT is
- How it works
- Why and when to use it
- How to implement it in a .NET
Core API
π What is JWT?
JWT stands for JSON Web Token. It’s a compact, URL-safe token
used to securely transmit information between two parties — typically
between a client and a server.
Unlike traditional session-based authentication
(which stores session data on the server), JWT is stateless. All the
information is stored in the token itself.
π§± Structure of a JWT
A JWT has three parts, separated by
dots:
xxxxx.yyyyy.zzzzz
1. Header
Specifies the type of token and the algorithm
used to sign it.
json
{
"alg":
"HS256",
"typ":
"JWT"
}
2. Payload
Contains the claims (data like user ID,
roles, expiration, etc.).
json
{
"sub":
"1234567890",
"name":
"John Doe",
"role":
"Admin",
"exp":
1717045110
}
3. Signature
Used to verify the token hasn’t been tampered
with.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
π How JWT Works (Authentication Flow)
- User logs in with credentials (e.g., email +
password).
- Server verifies credentials and generates a JWT.
- JWT is sent back to
the client (browser/mobile).
- Client stores JWT
(usually in localStorage or memory).
- On subsequent requests,
client sends the JWT in the Authorization header:
makefile
Authorization: Bearer eyJhbGciOi...
- Server verifies the token and grants or denies access.
⚙️
Why Use JWT?
✅ Stateless
– no need to store session on server
✅ Scalable – perfect for microservices and distributed apps
✅ Cross-platform – works with web, mobile, and APIs
✅ Self-contained – stores user info in the token itself
❌
When NOT to Use JWT
- When you need to revoke
tokens instantly (JWT is hard to revoke unless using blacklists)
- For large payloads
(tokens can get big)
- If you need to track
sessions closely on the server
π¨π» Example: JWT in .NET Core
1. Install NuGet Package
mathematica
Microsoft.AspNetCore.Authentication.JwtBearer
2. Configure JWT in Program.cs or Startup.cs
csharp
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("your_secret_key"))
};
});
3. Generate Token
csharp
var claims = new[]
{
new
Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new
Claim(ClaimTypes.Role, "Admin")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var creds = new SigningCredentials(key,
SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds
);
var jwt = new
JwtSecurityTokenHandler().WriteToken(token);
π Securing Endpoints with JWT
csharp
[Authorize]
[HttpGet("profile")]
public IActionResult GetProfile()
{
//
This will only run if a valid JWT is attached
return
Ok("This is a protected route");
}
Use [Authorize(Roles = "Admin")] to
restrict by role.
π§ͺ Tips & Best Practices
- π Use HTTPS to prevent token
interception
- ⏳ Set short expiration times for tokens
- π Consider using refresh tokens for
long sessions
- ❌ Don’t store tokens in localStorage if security is a concern —
consider HttpOnly cookies
- ✅ Validate tokens on every request
π Summary
Feature |
JWT |
Type |
Token-based auth |
Storage |
Client-side (localStorage, cookies) |
Scalable |
✅ Yes |
Stateless |
✅ Yes |
Secure |
✅ Yes
(with HTTPS & signing) |
Revocable |
❌ Not
easily (use blacklist) |
π― Final Thoughts
JWT is an essential tool in modern API
development. It’s secure, scalable, and perfect for stateless architectures.
Once you master JWT, you unlock the ability to secure your applications
confidently and efficiently.
Comments
Post a Comment