Question

I would like to remove csrf from my Express 3.0 application as i don't need it there. I use oauth to validate clients. Is the a middleware to whitelist API urls when using express.csrf()?

Was it helpful?

Solution

You can do that in two ways.

1.) Create a small middleware of your own to allow white list url patterns not to be blocked by csrf like;

var express = require("express");
var expressCsrf = express.csrf();
var app = express.createServer();

var customCsrf = function (req, res, next) {
    // I assume exact match, but you can use regex match here
  var csrfEnabled = true;
  var whiteList = new Array("/pattern1/param1","/pattern2/param2","/pattern3/param3");
  if (whiteList.indexOf(req.path) != -1) {
    csrfEnabled = false;
  }

  if (csrfEnabled) {
    expressCsrf(req, res, next);
  } else {
    next();
  }
}

app.use(customCsrf);
app.listen(3000);

2.) Use csrf middleware on your controllers you want to enable. For example, you want to use csrf check on profile save controller;

app.post("/profile/save", express.csrf(), function(req, res, next) {
    // put your code here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top