JWT tokens are typically valid until their expiration time, and without server-side tracking, there's no built-in way to invalidate them early — such as when a user logs out. This creates a potential security risk.
JWT (JSON Web Token) is a widely used standard for communicating securely between a server and a client. It is stateless, which makes it very fast, but this stateless nature introduces challenges — especially around logout and token invalidation.
User logs in by sending credentials:
{
"username": "r0ld3x",
"password": ""
}
Server verifies credentials and creates a JWT:
const jwt = require("jsonwebtoken");
const secret = "your-256-bit-secret";
const user = { id: 1 };
const payload = { id: user.id };
const token = jwt.sign(payload, secret, {
algorithm: "HS256",
header: { typ: "JWT" },
expiresIn: "30d"
});
console.log("JWT Token:", token);
Token is sent to the client, often via a cookie:
Set-Cookie: token=eyJhbGciOi...; HttpOnly; Secure
On each request, the client sends the token.
Introduce a server-side token/session store to handle:
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const secretKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
function encryptUserId(userId) {
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
let encrypted = cipher.update(userId.toString(), 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decryptUserId(encrypted) {
const [ivHex, encryptedData] = encrypted.split(':');
const decipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.from(ivHex, 'hex'));
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const token = encryptUserId(45);
console.log('Token:', token);
console.log('User ID:', decryptUserId(token));
Feature | JWT | Encrypted ID Token |
---|---|---|
Stateless | ✅ | ❌ |
Self-contained | ✅ | ❌ (DB lookup) |
Expirable | ✅ (with exp ) | ✅ (manual) |
Revocable | ❌ (unless stored) | ✅ |
Tamper-proof | ✅ (signed) | ✅ (encrypted) |
Confidential | ❌ | ✅ |
JWT is powerful, but you must extend it with server-side validation (blacklist/allowlist) or consider fully custom auth mechanisms to support logout and token revocation securely.