Implementing anti-CSRF (Cross-Site Request Forgery) measures is essential for protecting web applications from unauthorized actions. Here are several commonly used strategies to implement anti-CSRF protection in an application:
1. CSRF Tokens
Generate a Token:
Upon user session initiation (e.g., after logging in), generate a unique token and store it on the server side along with the user session.
Include Token in Forms:
Include the CSRF token as a hidden form field in all forms that perform state-changing operations (like POST requests):
On the server side, validate that the custom header is present and correct for state-changing requests.
4. Double Submit Cookies
Set a CSRF Cookie:
Send a CSRF token as a cookie along with your main application cookie.
Send Token with Requests:
Include the CSRF token in request bodies or headers. Your server-side logic then checks that the token matches the value in the cookie.
5. Check Referer/Origin Header
Validate the Referrer:
Validate the Referer or Origin headers on state-changing requests to ensure they originate from your domain.
6. Framework Support
Utilize Built-in Mechanisms:
Many web frameworks come with built-in CSRF protection mechanisms. For example:
Django: Automatic CSRF protection via middleware.
Spring: CSRF protection is enabled by default.
Ruby on Rails: Includes built-in CSRF tokens in forms.
Implementation Example
Here’s a simplified example using Node.js and Express:
1. Setup express and csurf package:
bash
npm install express csurf cookie-parser
2. Basic server setup:
javascript
const express = require('express');
const cookieParser = require('cookie-parser');
const csurf = require('csurf');
const app = express();
app.use(cookieParser());
app.use(express.urlencoded({ extended: true })); // For parsing form data
// CSRF protection middleware
const csrfProtection = csurf({ cookie: true });
app.use(csrfProtection);
// Route to serve form with CSRF token
app.get('/form', (req, res) => {
res.send(`<form action="/submit" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<button type="submit">Submit</button>
</form>`);
});
// Route to handle form submission
app.post('/submit', (req, res) => {
// Your form handling logic
res.send('Form submitted successfully!');
});
// Error handling middleware
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
// CSRF token validation failed
res.status(403).send('Invalid CSRF token');
} else {
next(err);
}
});
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
Conclusion
By adopting these practices, you can significantly reduce the risk of CSRF attacks in your web application. Always keep your libraries and frameworks up to date, and stay informed about security best practices.