How to Fix CSRF Token Validation Errors
In this tutorial, you'll learn about How to Fix CSRF Token Validation Errors. We cover key concepts, practical examples, and best practices.
CSRF (Cross-Site Request Forgery) token validation errors occur when a state-changing request (POST, PUT, DELETE) is received without a valid CSRF token, or the token validation logic has flaws.
Quick Fix
Wrong
// Accepting state-changing requests without CSRF token
app.post("/transfer", [](Request& req, Response& res) {
executeTransfer(req.param("to"), req.param("amount"));
res.send("OK");
});
An attacker can host <img src="https://bank.com/transfer?to=attacker&amount=10000"> on their site, and any logged-in user who visits it triggers a transfer.
Right
app.post("/transfer", [](Request& req, Response& res) {
std::string token = req.param("csrf_token");
if (!validateCsrfToken(req.session, token)) {
res.status(403).send("Invalid CSRF token");
return;
}
executeTransfer(req.param("to"), req.param("amount"));
res.send("OK");
});
Fix with server-side token generation
std::string generateCsrfToken(Session& session) {
std::string token = randomHexString(32);
session.csrfToken = token;
return token;
}
bool validateCsrfToken(Session& session,
const std::string& token) {
return constantTimeEquals(session.csrfToken, token);
}
Fix with SameSite cookies
response.setCookie("session", sessionId, {
.httpOnly = true,
.secure = true,
.sameSite = "Strict" // "Lax" for GET-only exceptions
});
Fix with custom header check
// Require a custom header that browsers cannot set cross-origin
if (req.header("X-Requested-With") != "XMLHttpRequest") {
res.status(403).send("CSRF protection");
}
Prevention
- Include CSRF tokens in all state-changing forms and AJAX requests.
- Validate tokens server-side with constant-time comparison.
- Use SameSite=Strict or SameSite=Lax cookie attribute.
- Require custom headers for API routes.
- Set short token expiration times (30-60 minutes).
DodaTech Tools
Doda Browser's security auditor checks for CSRF token implementation across web forms and API endpoints. DodaZIP archives security audit trails. Durga Antivirus Pro detects CSRF attacks by analyzing cross-origin request patterns.
Common Mistakes with token validation
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CSRF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro