Search code examples
node.jscsrfexpress-4

Node.js use csurf conditionally with express 4


I try to use csurf on just a few routes in my express app. that's the approach:

var express       = require('express');
var session       = require('express-session');
var csrf          = require('csurf');

// some more stuff

var csrfExclusion = ['/myApi','/unsecure'];

var app   = express();

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
  }
});

app.use(conditionalCSRF);

even tried:

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf(req, res, next);
    next();
  }
});

and

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
    next();
  }
});

But this gives me an error: Object # has no method 'csrfToken'

How can I use csurf conditionally. The documentation only gives information to use it on all routes in the express app with

app.use(csrf());

But that's not what I want, I want to exclude some route...

kindly... martin

UPDATE:

finally it works. I did the following:

app.use(function(req, res, next){
  if (csrfExclusion.indexOf(req.path) !== -1) {
  next();
}
  else {
  csrf()(req, res, next);
});

This adds the csrf middleware conditionally. But I really think it's kind of strange to call it like this:

csrf()(req, res, next);

I even do not get the syntax...


Solution

  • According to this you need to split it up into two routers, one using csurf and one not. You'd then apply the middleware to the router instead of the app.

    var routes = express.Router();
    var csrfExcludedRoutes = express.Router();
    
    routes.use(csrf());
    
    routes.get('/', function(req, res) {
        //has req.csrfToken()
    });
    
    csrfExcludedRoutes.get('/myApi', function(req, res) {
        //doesn't have req.csrfToken()
    });