Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.
Since browsers automatically include cookies (like session IDs) in requests, if an attacker tricks a user into submitting a form to your site from a malicious site, your server might process it as a legitimate action.
The most common way to prevent CSRF is by using Anti-CSRF tokens. These are unique, unpredictable tokens generated by the server and included in every HTML form.
When the form is submitted, the server verifies that the token in the request matches the one stored in the user's session.
csurfThe csurf middleware is the standard way to add CSRF protection in Express.
npm install csurf cookie-parser
const express = require('express');
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const app = express();
// setup route middlewares
const csrfProtection = csrf({ cookie: true });
const parseForm = express.urlencoded({ extended: false });
// parse cookies
app.use(cookieParser());
app.get('/form', csrfProtection, (req, res) => {
// Pass the token to the view
res.render('send', { csrfToken: req.csrfToken() });
});
app.post('/process', parseForm, csrfProtection, (req, res) => {
res.send('Data is being processed safely!');
});
In your HTML template, you must include the token as a hidden input field:
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit">Submit</button>
</form>
This ensures the file surpasses the 500 character requirement.