JAVASCRIPT
Implement Cross-Site Request Forgery (CSRF) Protection
Protect your Node.js Express application from CSRF attacks by implementing token-based verification using the `csurf` middleware for enhanced form security.
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const csrf = require('csurf');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// Middleware setup
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'super_secret_key_for_session',
resave: false,
saveUninitialized: true,
cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true, sameSite: 'lax' }
}));
// CSRF middleware
const csrfProtection = csrf({ cookie: true });
// Example routes
app.get('/', csrfProtection, (req, res) => {
const csrfToken = req.csrfToken();
res.send(`
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${csrfToken}">
<input type="text" name="data" placeholder="Enter data">
<button type="submit">Submit</button>
</form>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// If we get here, the CSRF token was valid
res.send(`Data received: ${req.body.data}`);
});
// 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);
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: This snippet demonstrates how to implement CSRF protection in an Express.js application using the `csurf` middleware. It generates a unique, secret token for each user session and embeds it into forms (as a hidden input field) or headers. When a form is submitted, the server verifies this token against the one stored in the session or cookie. If the tokens don't match, the request is rejected, preventing malicious cross-site requests from being executed without the user's consent. This setup also includes secure session and cookie configurations.