CSRF Token is one of the most commonly used and effective protection mechanisms against Cross-Site Request Forgery attacks.
Basic Principles of CSRF Token
A CSRF Token is a randomly generated, unpredictable string that the server generates when a user visits a protected page and embeds it into the form or passes it to the client through other means. When the user submits the form, the server verifies whether the Token included in the request matches the Token stored on the server.
Token Generation and Storage
-
Generation Phase:
- Use cryptographically secure random number generators
- Token should be long enough (at least 128 bits)
- Include information such as timestamps or session IDs
- Can use UUID or other unique identifiers
-
Storage Methods:
- Server-side Session: Most common method, storing Token in user Session
- Encrypted Cookie: Store encrypted Token in Cookie
- Database: Store Token associated with user in database
Token Verification Process
- When user accesses form page, server generates Token
- Token is embedded in form's hidden field
- When user submits form, Token is sent to server with request
- Server verifies whether Token in request matches Token in Session
- If verification succeeds, process request; if fails, reject request
Implementation Example
javascript// Generate Token function generateCSRFToken() { return crypto.randomBytes(32).toString('hex'); } // Middleware to verify Token function csrfProtection(req, res, next) { const token = req.body._csrf || req.headers['x-csrf-token']; if (token !== req.session.csrfToken) { return res.status(403).send('Invalid CSRF token'); } next(); }
Security Considerations for Token
- One-time use: Token should be updated after each request
- Time validity: Token should have expiration time
- Uniqueness: Each user session should have independent Token
- Unpredictability: Use cryptographically secure random number generators
- HTTPS transmission: Ensure Token is not stolen during transmission
Coordination with Other Protection Measures
CSRF Token is usually used in conjunction with other protection measures:
- SameSite Cookie attribute
- Referer header verification
- Custom HTTP headers
This multi-layer protection strategy can provide more comprehensive security protection.