Tool for HR, Hiring Managers, and the Leadership Team

JWT Token Authentication — Interview Guide

JWT Token Authentication — Interview Guide (With Examples)

JWT is one of the most commonly asked interview topics for backend developers, especially if you work with .NET / APIs / Angular / React.

Let's break it down in simple interview-friendly way 👇

1. What is JWT?

JWT (JSON Web Token) is a compact, secure way to authenticate users and transfer information between client and server.

A JWT token is:

✅ Stateless
✅ Secure
✅ Self-contained
✅ Widely used in REST APIs

JWT stands for JSON Web Token (JWT)

2. Why Do We Need JWT?

Before JWT:

  • Server creates Session

  • Stores session in memory/database

  • Client sends Session ID

Problems ❌

  • Hard to scale

  • Server memory usage

  • Load balancing issues

JWT solves this by:

✔ No server session
✔ Stateless authentication
✔ Easy scaling

3. Real World Example

When you login to:

  • Banking website

  • Gmail

  • Any API based system

Flow:

  1. User logs in

  2. Server validates credentials

  3. Server generates JWT token

  4. Client stores token

  5. Client sends token in every request

  6. Server validates token

4. JWT Structure

JWT has 3 parts

Header.Payload.Signature

Example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNhbXAiLCJpYXQiOjE1MTYyMzkwMjJ9
.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

5. JWT Structure Explained

1. Header

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg → Algorithm

  • typ → Token type

2. Payload

Contains user data (Claims)

{
  "userId": 1,
  "username": "Sampath",
  "role": "Admin"
}

This data is called Claims

Types:

  • Registered Claims

  • Public Claims

  • Private Claims

Example:

sub → subject
exp → expiration
iat → issued at

3. Signature

Signature is created using:

Header + Payload + Secret Key

This ensures token is not modified

6. JWT Authentication Flow

Step-by-Step:

User → Login
     ↓
Server → Validate credentials
     ↓
Server → Generate JWT
     ↓
Client → Store token
     ↓
Client → Send token in header
     ↓
Server → Validate token
     ↓
Server → Return data

7. Example Request

Login Request

POST /login

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

8. Sending JWT Token

Client sends token in Authorization header

Authorization: Bearer <token>

Example:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

9. JWT Example in C# (.NET)

Using ASP.NET Core

Generate Token

var claims = new[]
{
    new Claim(ClaimTypes.Name, user.Username),
    new Claim(ClaimTypes.Role, user.Role)
};

var key = new SymmetricSecurityKey(
    Encoding.UTF8.GetBytes("YourSecretKey"));

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);

10. Configure JWT Authentication

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters =
        new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
});

11. Protect API Endpoint

[Authorize]
[HttpGet]
public IActionResult GetUsers()
{
    return Ok();
}

Only authenticated users can access this endpoint.

12. Advantages of JWT

✅ Stateless
✅ Scalable
✅ Secure
✅ Works well with APIs
✅ Cross-platform

13. Disadvantages

❌ Cannot revoke easily
❌ Token size larger
❌ Must manage expiration

14. JWT vs Session Authentication

Feature JWT Session
Stateless Yes No
Scalable Yes No
Server Memory No Yes
Mobile Friendly Yes No

15. Interview Questions (Very Important)

Basic Questions

1. What is JWT?
JWT is a secure token used for authentication.

2. What are parts of JWT?
Header, Payload, Signature

3. Where is JWT stored?

  • LocalStorage

  • SessionStorage

  • Cookies

Intermediate Questions

4. What is Claim?

Claims are user data inside JWT.

Example:

UserId
Role
Email

5. What is Bearer Token?

Token sent in Authorization header.

Authorization: Bearer token

Advanced Questions

6. Is JWT secure?

Yes, when:

  • HTTPS used

  • Short expiration used

  • Secret key protected

7. Can JWT be revoked?

Not easily. Solutions:

  • Short expiry

  • Refresh tokens

  • Blacklist tokens

16. JWT with Refresh Token (Interview Favorite)

Flow:

Access Token → Short expiry (15 mins)
Refresh Token → Long expiry (7 days)

When token expires:

  • Client uses Refresh Token

  • Server generates new Access Token

17. JWT vs OAuth (Interview Question)

JWT = Token format
OAuth 2.0 = Authorization framework

They are different but often used together.

18. Best Practices

✅ Use HTTPS
✅ Short expiry
✅ Use refresh tokens
✅ Don't store sensitive data in payload
✅ Use strong secret key

19. Real Interview Answer (Perfect Short Answer)

JWT is a stateless authentication mechanism where server generates a token after user login. The client sends this token in Authorization header for each request. The server validates the token signature and allows access to protected resources.