πŸ” 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)

  1. User logs in with credentials (e.g., email + password).
  2. Server verifies credentials and generates a JWT.
  3. JWT is sent back to the client (browser/mobile).
  4. Client stores JWT (usually in localStorage or memory).
  5. On subsequent requests, client sends the JWT in the Authorization header:

makefile

Authorization: Bearer eyJhbGciOi...

  1. 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

Popular posts from this blog

Scrutor the built-in Dependency Injection (DI)

πŸ”Œ Extension Methods in C#: Power Up Your Code Without Modifying It

πŸ§… Understanding the Onion Architecture: A Clean Approach to Building Scalable Applications

Understanding Dependency Injection: A Modern Guide for Developers

🌐 CORS in .NET Explained: Solving the Cross-Origin Problem Like a Pro

Ensuring Data Integrity: The Backbone of Reliable Systems

πŸ”— SQL JOINs Explained: Mastering Table Relationships

πŸ—‚️ DROP vs DELETE vs TRUNCATE in SQL: What’s the Difference?

πŸ›‘️ SIEM Logs Explained: How to Build Secure and Auditable .NET Apps