In this lesson, you will learn how to enforce short-lived access tokens to significantly reduce the impact of a compromised credential.
The Security Dilemma of Persistence
When you issue a JSON Web Token (JWT) to a user, that token acts as a "digital key" to your application. If a token has an infinite lifespan, an attacker who steals it—perhaps through a cross-site scripting (XSS) attack or server log exposure—possesses permanent access to that user's account. To mitigate this risk, we implement a "window of opportunity" constraint by setting a strict expiration time.
Setting the Expiration (exp)
The JWT standard includes an exp (expiration) claim. When you generate a token in Node.js using a library like jsonwebtoken, you should define this value in seconds or a relative time string. A common industry standard for access tokens is between 5 and 15 minutes.
Here is how you implement this during token creation:
const jwt = require('jsonwebtoken');
const generateAccessToken = (user) => {
// Enforce a 15-minute expiration
return jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {
expiresIn: '15m'
});
};
Why Short-Lived Tokens?
By forcing tokens to expire quickly, you ensure that even if an attacker manages to exfiltrate a token, their access window is extremely narrow. Once the 15 minutes pass, the token becomes useless, and any attempt to use it will be rejected by your middleware during the signature verification step.
This strategy forces a trade-off: it improves security but requires the client to handle the expiration gracefully. Usually, this involves a "silent" request—often using a longer-lived refresh token—to acquire a new access token without interrupting the user's workflow. By keeping the access token short-lived, you effectively quarantine the damage potential of any single compromised credential.
Key Takeaway: By setting short expiration times on access tokens, you minimize the duration an attacker can exploit a stolen session, turning a potentially catastrophic breach into a minor, temporary inconvenience.