Token Rotation and Lifecycle
What you'll learn: How to manage CSRF token generation, expiration, and rotation to maximize security and minimize attack windows.
Why Token Lifecycle Matters
A CSRF token isn't a "set it and forget it" defense. Just like you wouldn't use the same password forever, CSRF tokens need active lifecycle management. If a token lives too long or is reused indefinitely, attackers have more time to steal it (via XSS, network sniffing, or browser history) and exploit it.
Core Lifecycle Stages
Generation: Create a cryptographically random, unique token when a user starts a session or loads a form. This token should be unpredictable and tied to that specific user's session.
Expiration: Set tokens to expire after a reasonable timeframe—perhaps after 15-30 minutes of inactivity, or when the session ends. Expired tokens should be rejected server-side.
Rotation: Generate a new token after each sensitive request (like password changes or financial transactions) or after each page load. This per-request rotation means even if an attacker obtains a token, it's already stale by the time they try to use it.
The Rotation Analogy
Think of CSRF tokens like temporary building access codes. A contractor gets a code that expires at day's end (expiration). After completing sensitive work in the server room, they're issued a new code for the next task (rotation). This way, if someone overhears an old code, it's already useless.
Implementation Considerations
- Store active tokens server-side (in session storage) with timestamps
- Validate both token presence and freshness on every protected request
- Invalidate old tokens immediately after rotation
- Consider per-form tokens for highly sensitive operations
Key Takeaway:
CSRF tokens should be treated as short-lived secrets—generate them unpredictably, expire them promptly, and rotate them frequently to minimize the window of opportunity for attackers.