JAVASCRIPT
Protect Against Cross-Site Request Forgery (CSRF)
Implement robust CSRF protection in your Node.js Express application to prevent attackers from tricking users into executing unwanted actions.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csurf = require('csurf');
const app = express();
// Configure middleware
app.use(cookieParser());
app.use(express.urlencoded({ extended: false })); // for parsing application/x-www-form-urlencoded
// Session middleware configuration (use a secure store in production)
app.use(session({
secret: 'aVeryStrongSecretKeyForSessions',
resave: false,
saveUninitialized: true,
cookie: { secure: true } // Ensure cookies are only sent over HTTPS
}));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
// Use EJS for templating (or any other view engine)
app.set('view engine', 'ejs');
// Routes
app.get('/', csrfProtection, (req, res) => {
res.render('index', { csrfToken: req.csrfToken() });
});
app.post('/process', csrfProtection, (req, res) => {
console.log('Processing form data:', req.body);
res.send('Form processed successfully!');
});
// Error handling for CSRF issues
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).send('Invalid CSRF token.');
} else {
next(err);
}
});
// Example EJS template (views/index.ejs):
// <form action="/process" method="POST">
// <input type="hidden" name="_csrf" value="<%= csrfToken %>">
// <input type="text" name="item" placeholder="Enter item">
// <button type="submit">Submit</button>
// </form>
app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This snippet demonstrates how to protect against Cross-Site Request Forgery (CSRF) attacks in a Node.js Express application using the `csurf` middleware. CSRF allows attackers to trick authenticated users into executing unwanted actions on a web application. The `csurf` middleware generates a unique, unpredictable token for each user session. This token is then embedded in forms as a hidden field. When the form is submitted, `csurf` verifies that the token sent in the request matches the one stored in the session/cookie. If they don't match, the request is blocked, preventing malicious requests from external sites from being processed. This requires `cookie-parser` and `express-session` for session management and token storage.