JSON Web Token (JWT) Authentication: A Comprehensive Guide

Listen to this Post

JSON Web Token (JWT) authentication is a widely-used method for securing APIs and web applications. This article will walk you through the steps of JWT authentication, provide practical examples, and share best practices for secure implementation.

Step 1: User Authentication (Login)

1. User Inputs Credentials:

The user provides their credentials (e.g., username and password) via a login form or API request.

2. Server Verifies Credentials:

The server verifies the credentials against stored data (e.g., a database or authentication service).

3. JWT is Generated:

If the credentials are valid, the server generates a JWT. The JWT contains:
– Header: Specifies the token type (JWT) and signing algorithm (e.g., HS256).
– Payload: Includes claims (data about the user, like userID and role).
– Signature: Ensures the token’s integrity by signing the header and payload with a secret key or private key.

4. JWT is Sent to the User:

The server sends the generated JWT to the client in the response (usually in the HTTP response body or a cookie).

Step 2: Token Storage

The client (e.g., a browser or mobile app) stores the JWT securely:
– Local Storage or Session Storage: For single-page applications (SPAs).
– HTTP-Only Cookies: For added security, protecting against XSS attacks.

Step 3: Making an Authenticated Request

1. Client Includes JWT in Request:

For subsequent API requests, the client includes the JWT in the Authorization header:

Authorization: Bearer <JWT>

Alternatively, the token may be sent via a cookie if stored that way.

2. Server Verifies JWT:

The server extracts the JWT from the request and validates it by:
– Decoding it to check the claims in the payload.
– Verifying the signature to ensure the token hasn’t been tampered with.
– Checking the token’s validity (e.g., expiration date, audience, issuer).

Step 4: Access Granted or Denied

1. Valid JWT:

If the JWT is valid, the server processes the request and responds with the requested resource/data.

2. Invalid JWT:

If the JWT is invalid (e.g., expired, malformed, or tampered with), the server responds with an error (e.g., HTTP 401 Unauthorized).

Step 5: Token Expiry and Renewal

1. Token Expiry:

JWTs often include an `exp` (expiration) claim to define their validity period. After expiration, the client must request a new token.

2. Token Refresh:

A Refresh Token mechanism is often used for re-authentication without requiring the user to log in again. The client sends the refresh token to the server to get a new JWT.

Advantages of JWT

  • Stateless Authentication: No need to store session data on the server.
  • Compact and Portable: Easy to transmit over HTTP.
  • Secure: Signature ensures integrity.

You Should Know:

1. Generating a JWT in Python

import jwt
import datetime

<h1>Secret key for signing the token</h1>

SECRET_KEY = "your_secret_key"

<h1>Payload data</h1>

payload = {
"user_id": 123,
"username": "john_doe",
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}

<h1>Generate JWT</h1>

token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
print("Generated JWT:", token)

2. Verifying a JWT in Python

try:
decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
print("Decoded JWT:", decoded)
except jwt.ExpiredSignatureError:
print("Token has expired.")
except jwt.InvalidTokenError:
print("Invalid token.")

3. Linux Command to Check JWT Expiry

echo "<JWT>" | cut -d '.' -f 2 | base64 --decode | jq

This command decodes the JWT payload and checks the `exp` field.

4. Windows Command to Test JWT Authentication

Invoke-WebRequest -Uri "https://api.example.com/resource" -Headers @{ "Authorization" = "Bearer <JWT>" }

5. Using cURL to Test JWT Authentication

curl -H "Authorization: Bearer <JWT>" https://api.example.com/resource

Common Security Best Practices

1. Use HTTPS to encrypt communication.

2. Store tokens securely (e.g., use HTTP-only cookies).

3. Implement short token lifetimes and refresh mechanisms.

4. Validate claims like `exp`, `iss`, and `aud`.

What Undercode Say:

JWT authentication is a powerful tool for securing modern web applications and APIs. By following the steps outlined above, you can implement a robust authentication system that is both secure and scalable. Always adhere to security best practices, such as using HTTPS, secure token storage, and proper token validation. Additionally, leverage tools like Python’s `jwt` library and Linux/Windows commands to streamline your development and testing processes.

Expected Output:

  • Generated JWT: A compact, URL-safe token.
  • Decoded JWT: A JSON object containing user claims.
  • API Response: Access to protected resources or an error message for invalid tokens.

For further reading, refer to the JWT Official Documentation.

References:

Reported By: Harisha Warnakulasuriya – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image