# Understanding JWT Authentication

Listen to this Post

JWTs (JSON Web Tokens) are widely used in modern authentication systems. They provide a compact and self-contained way to securely transmit information between parties as a JSON object. Let’s break down how they work and explore practical implementations.

What’s Inside a JWT?

A JWT consists of three parts, separated by dots (.):

1. Header (Metadata)

Specifies the token type (typ) and signing algorithm (alg).

Example:

{ 
"alg": "HS256", 
"typ": "JWT" 
}

### **2. Payload (Claims & User Data)**

Contains claims (statements about the user) and additional data.

Types of claims:

  • Public: Openly shareable (e.g., name, email).
  • Registered: Standard claims like `sub` (subject), `iat` (issued at).
  • Private: Custom claims for specific use cases.

Example:

{ 
"sub": "12345", 
"name": "John Doe", 
"admin": true, 
"iat": 1716230911 
}

### **3. Signature (Security Layer)**

Ensures the token hasn’t been tampered with. Generated using:
[/json]

HMACSHA256(

base64UrlEncode(header) + “.” + base64UrlEncode(payload),

secret_key

)


How JWT Authentication Works? 
1. User Login: Client sends credentials (e.g., username/password). 
2. Token Issuance: Server validates credentials and issues a JWT. 
3. Access Requests: Client sends JWT in the `Authorization: Bearer <token>` header. 
4. Verification: Server validates the JWT’s signature and grants access.

Why Use JWTs? 
✅ Stateless: No server-side session storage required. 
✅ Fast: Avoids database lookups for validation. 
✅ Secure: Tamper-proof when signed correctly.

<h1>You Should Know:</h1>

<ol>
<li>Generating a JWT in Linux (Using OpenSSL) 
[bash]</li>
</ol>

<h1>Generate a secret key</h1>

openssl rand -hex 32

<h1>Manually create a JWT (header + payload + signature)</h1>

echo -n '{"alg":"HS256","typ":"JWT"}' | base64 | sed 's/+/-/g; s/\//<em>/g; s/=//g' 
echo -n '{"sub":"12345","name":"John Doe","admin":true}' | base64 | sed 's/+/-/g; s/\//</em>/g; s/=//g' 

### **2. Validating a JWT in Node.js**

const jwt = require('jsonwebtoken'); 
const token = "your.jwt.token"; 
const secret = "your-secret-key";

try { 
const decoded = jwt.verify(token, secret); 
console.log("Valid JWT:", decoded); 
} catch (err) { 
console.error("Invalid JWT:", err.message); 
}

### **3. Decoding a JWT in Python**

import jwt

token = "your.jwt.token" 
secret = "your-secret-key"

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

### **4. Using JWTs in APIs (cURL Example)**


<h1>Request with JWT</h1>

curl -H "Authorization: Bearer your.jwt.token" https://api.example.com/data

<h1>Decode JWT in CLI (Linux)</h1>

echo "your.jwt.token" | cut -d '.' -f 2 | base64 -d 

### **5. Security Best Practices**

  • Never store sensitive data in JWTs (they are base64-encoded, not encrypted).
  • Use HTTPS to prevent token interception.
  • Set short expiration times (exp claim).
  • Rotate secrets periodically.

# **What Undercode Say:**

JWTs are powerful for stateless authentication but must be implemented securely. Always:

✔ **Verify signatures** before trusting a JWT.

✔ **Use strong secrets** (256-bit+ keys).

Avoid storing tokens in localStorage (use HttpOnly cookies for web apps).

For further learning:

# **Expected Output:**

A secure, stateless authentication system using JWTs with proper validation and security measures.

References:

Reported By: Akashsinnghh Understanding – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image