0
0
Expressframework~10 mins

CSRF protection in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - CSRF protection
Client sends request
Server checks CSRF token
Process
Send response
The server checks if the CSRF token sent by the client matches the expected token before processing the request.
Execution Sample
Express
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');
const app = express();
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(csrf({ cookie: true }));
app.get('/form', (req, res) => {
  res.send(`<form method="POST" action="/form">
    <input type="hidden" name="_csrf" value="${req.csrfToken()}">
    <button type="submit">Submit</button>
  </form>`);
});
app.post('/form', (req, res) => {
  res.send('Form submitted');
});
This code adds CSRF protection middleware to an Express app and handles a POST form submission.
Execution Table
StepRequest TypeCSRF Token PresentToken Valid?ActionResponse
1GET /formNo (token generated)N/AGenerate token and send formForm with CSRF token
2POST /formYes (token sent)YesProcess form dataForm submitted
3POST /formYes (token sent)NoReject request403 Forbidden
4POST /formNo tokenNoReject request403 Forbidden
💡 Requests without a valid CSRF token are rejected to prevent CSRF attacks.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
csrfTokenundefinedgenerated token stringtoken string from clienttoken string from clientundefined
Key Moments - 2 Insights
Why does the server reject a POST request without a CSRF token?
Because the CSRF middleware requires a valid token to confirm the request is from the trusted client, as shown in execution_table rows 3 and 4.
When is the CSRF token generated and sent to the client?
During a safe GET request, the server generates and sends the token embedded in the form, as shown in execution_table row 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 2 when the token is valid?
AThe server generates a new CSRF token
BThe server rejects the request with 403 Forbidden
CThe server processes the form data and sends a success response
DThe server ignores the token and processes the request
💡 Hint
Refer to execution_table row 2 under 'Action' and 'Response'
At which step does the server generate the CSRF token?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check execution_table row 1 where the token is generated and sent
If the client sends a POST request without any CSRF token, what response will the server give?
A200 OK with form submitted message
B403 Forbidden error
CRedirect to GET /form
D500 Internal Server Error
💡 Hint
See execution_table row 4 where no token causes rejection
Concept Snapshot
CSRF protection in Express:
- Use csurf middleware to add CSRF tokens
- Server generates token on safe requests (GET)
- Client sends token with unsafe requests (POST)
- Server validates token before processing
- Reject requests with missing or invalid tokens
- Prevents unauthorized cross-site requests
Full Transcript
CSRF protection in Express works by generating a unique token for each user session during safe requests like GET. This token is sent to the client embedded in forms. When the client submits a form with a POST request, it must include this token. The server checks the token's validity before processing the request. If the token is missing or invalid, the server rejects the request with a 403 Forbidden error. This process prevents attackers from tricking users into submitting unwanted requests from other sites. The csurf middleware handles token generation and validation automatically. The flow starts with the client requesting a form, the server generating and sending a token, then the client submitting the form with the token, and the server validating it before accepting the data.