To invalidate a JWT token effectively, here are some common methods:
1. Blacklist Tokens:
- Store invalidated tokens in a database or cache (e.g., Redis).
- Check this blacklist on each request to verify if the token is revoked.
const token = "user_jwt_token";
blacklist.add(token);
2. Token Versioning:
- Include a version or session_id in the user’s JWT claims.
- Store the current version/session ID in the database, updating it on logout or token reset.
- During authentication, compare the token’s version/session ID to the stored value.
if (tokenVersion !== storedTokenVersion) {
throw new Error("Token invalidated");
}
3. Short Token Expiration with Refresh Tokens:
- Use short-lived access tokens and issue long-lived refresh tokens.
- Re-authenticate or reissue the token when the access token expires, requiring server validation.
const accessToken = generateAccessToken(user, { expiresIn: "15m" });
4. Revoke All Tokens by Updating User Secrets:
- Update a “secret” or “salt” stored in the user’s database record upon logout or revocation.
- Use this updated secret to sign new tokens, invalidating old ones.
const newSecret = generateNewSecret();
5. Use Token Revocation Lists in Auth Servers:
If using a centralized authentication server, leverage its built-in mechanisms for token revocation, which often include revocation lists or caches.