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.
Jump into concepts and practice - no test required
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'); });
| Step | Request Type | CSRF Token Present | Token Valid? | Action | Response |
|---|---|---|---|---|---|
| 1 | GET /form | No (token generated) | N/A | Generate token and send form | Form with CSRF token |
| 2 | POST /form | Yes (token sent) | Yes | Process form data | Form submitted |
| 3 | POST /form | Yes (token sent) | No | Reject request | 403 Forbidden |
| 4 | POST /form | No token | No | Reject request | 403 Forbidden |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| csrfToken | undefined | generated token string | token string from client | token string from client | undefined |
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
csurf package?csurf middleware is used as csurf({ cookie: true }) to enable cookie-based CSRF tokens.app.post('/submit', csurf({ cookie: true }), (req, res) => {
res.send('Form submitted');
});csurf middleware but your form keeps failing CSRF validation. Which of these is the most likely cause?csurf with cookie-based tokens and render the token in a form. Which code snippet correctly sets up the middleware and passes the token to the template?csurf({ cookie: true }) to enable cookie-based CSRF tokens.req.csrfToken() as a functionreq.csrfToken(), not just reference the function.csrfToken in the render call for the form to use.