JAVASCRIPT
Implement CSRF Protection in Node.js Express Applications
Add Cross-Site Request Forgery (CSRF) protection to your Express.js applications using the csurf middleware to secure form submissions and state-changing requests.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csrf = require('csurf');
const app = express();
const port = 3000;
// Middleware setup
app.use(express.urlencoded({ extended: false })); // For parsing application/x-www-form-urlencoded
app.use(cookieParser());
app.use(session({
secret: 'supersecretkeyforcsrf',
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production' } // Use secure cookies in production
}));
// CSRF middleware setup
const csrfProtection = csrf({ cookie: true });
// Define a route that uses CSRF protection
app.get('/', csrfProtection, (req, res) => {
// Pass the CSRF token to the client-side for form submission
res.send(`
<h1>Submit Data Securely</h1>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<label for="data">Data:</label>
<input type="text" id="data" name="data">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// If we reach here, CSRF token was valid
console.log('Received data:', req.body.data);
res.send('Data processed securely!');
});
// Error handler for CSRF tokens
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('Invalid CSRF token.');
} else {
next(err);
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using the 'csurf' middleware. CSRF tokens are generated and embedded in forms. On submission, the server verifies the token against the one stored in the user's session. This ensures that state-changing requests originate from your application, not from a malicious third-party site, safeguarding against unauthorized actions.