Synchronize Your Tokens as Part of CSRF Protection

The most common CSRF protection is randomly generating a token for the form or session and always including it as part of a POST request. Every request is validated by comparing the submitted value with the expected token value. If the values match, the request is valid. There are several modules to choose from, but we’ll take a look at csurf,[80] which used to be part of express.

​ app.use(cookieParser());
​ app.use(session({
​  secret: ​'this is a nice secret'​,
​  resave: ​false​,
​  saveUninitialized: ​true​
​ }));
​ app.use(bodyParser.urlencoded());
​ app.use(csurf()); ​// Include csurf middleware​
​ 
​ ​// Show form​
​ app.get(​'/'​, ​ ...

Get Secure Your Node.js Web Application now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.