Express CSRF token validation Express CSRF token validation express express

Express CSRF token validation


Based on the amount of code you shared, I will mention a few things that don't look quite right to me:

1 . You may need to swap the lines below so that csrf runs before the routes.

app.use(csrf());app.use(app.router);

2 . The csrftoken setup needs to also be placed before the routes.

app.use(csrf());app.use(function (req, res, next) {  res.cookie('XSRF-TOKEN', req.csrfToken());  res.locals.csrftoken = req.csrfToken();  next();});app.use(app.router);

3 . You'll need to use locals.csrftoken in your form:

<form action="/process" method="POST">  <input type="hidden" name="_csrf" value="<%= csrftoken %>">  Favorite color: <input type="text" name="favoriteColor">  <button type="submit">Submit</button></form>


the token in the cookie will be completely different than the one in the express session. you want to check for one or the other not both.

i would disable the cookies entirely! as it worked for me.

var csrfProtection = csurf({ cookie: false });

the author mentions it herehttps://github.com/expressjs/csurf/issues/52

next you want to the "X-CSRF-Token" to the header on ajax post found here:Express.js csrf token with jQuery Ajax


Below code is working for me. Let me know in case you still face issue.

As mentioned that you wish to use cookies, you have make csurf aware that you are using cookies for setting the CSRF token.

Step1: Configuration

var csrf = require('csurf');var cookieparser= require('cookie-parser'); //cookieparser must be placed before csrf app.use(bodyparser.urlencoded({extended:false}));app.use(cookieParser('randomStringisHere222'));app.use(csrf({cookie:{key:XSRF-TOKEN,path:'/'}}));//add the your app routes hereapp.use("/api", person);app.use("/", home);

Step2: In the route,

res.render('myViewPage',{csrfTokenFromServer:req.csrfToken()}); 

Step3: Include a hidden field in the HTML for csrf token Example:

<form action="/api/person" method="POST">      <input type="hidden" name="_csrf" value=<%=csrfTokenFromServer %> />      First name:<br>      <input type="text" name="firstname" value="">      <br>      Last name:<br>      <input type="text" name="lastname" value="">      <br><br>      <input type="submit" value="Submit"> </form>