This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
XSRF/CSRF Protection Guide
What Is CSRF?
Cross-Site Request Forgery (CSRF or XSRF) is an attack that forces an authenticated user to execute unwanted actions on a web application. The attacker crafts a malicious page that, when visited by the victim, automatically submits a request to the target application using the victim's existing session cookies.
Attack Scenario
- Alice logs into
bank.example.comand has a valid session cookie.
2\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\. Alice visits evil.com, which contains an auto-submitting form targeting bank.example.com/transfer. 3\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\. The browser automatically includes Alice's session cookie with the request. 4\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\. The bank processes the transfer, believing Alice authorized it.
Defense 1: CSRF Tokens (Synchronizer Token Pattern)
The server embeds a unique, unpredictable token in each form or request. The server validates the token on state-changing requests.
Server-Side Implementation (Express)
const crypto = require('crypto');
function generateCSRFToken(req) {
const token = crypto.randomBytes(32).toString('hex');
req.session.csrfToken = token;
return token;
}
function csrfMiddleware(req, res, next) {
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(req.method)) {
const token = req.headers['x-csrf-token']
|| req.body._csrfToken;
if (!token || token !== req.session.csrfToken) {
return res.status(403).json({
error: 'CSRF validation failed'
});
Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.
Found this useful? Check out more developer guides and tool comparisons on AI Study Room.
Top comments (0)