JAVASCRIPT
Implement CSRF Protection with Express and `csurf`
Protect web applications from Cross-Site Request Forgery (CSRF) attacks by integrating a token-based middleware in Express.js for secure form submissions.
const express = require('express');
const cookieParser = require('cookie-parser');
const csurf = require('csurf');
const bodyParser = require('body-parser');
const app = express();
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
app.get('/', csrfProtection, (req, res) => {
res.send(`
<html>
<body>
<h1>Welcome</h1>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<label for="message">Message:</label>
<input type="text" id="message" name="message">
<button type="submit">Submit</button>
</form>
</body>
</html>
`);
});
app.post('/process', csrfProtection, (req, res) => {
// Access req.body.message and handle the form submission
res.send(`Message received: ${req.body.message} (CSRF token valid)`);
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
How it works: This snippet demonstrates how to integrate CSRF protection in an Express.js application using the `csurf` middleware. It generates a unique CSRF token for each request, embeds it into forms as a hidden field, and validates the token upon form submission, effectively preventing Cross-Site Request Forgery (CSRF) attacks by ensuring that incoming requests are legitimate.