Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable csrf validation for some requests on Express

I'm writing a small web app with Node.js using the Express framework. I'm using the csrf middleware, but I want to disable it for some requests. This is how I include it in my app:

var express = require('express');
var app = express();

app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.cookieSession({secret: 'secret'}));
app.use(express.csrf());

I want to set a POST route without the csrf control.

like image 326
Giorgio Polvara - Gpx Avatar asked Nov 22 '12 16:11

Giorgio Polvara - Gpx


Video Answer


4 Answers

There are several possible approaches. You basically need to understand what is the simplest and most correct rule to decide whether or not to use the csrf middleware. If you want csrf most of the time, except for a small whitelist of request patterns, follow the example in this answer I have about conditional logging middleware (copied below for convenience).

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

var conditionalCSRF = function (req, res, next) {
  //compute needCSRF here as appropriate based on req.path or whatever
  if (needCSRF) {
    csrf(req, res, next);
  } else {
    next();
  }
}

app.use(conditionalCSRF);
app.listen(3456);

Another approaches could be only using the middleware on a certain path like app.post('/forms/*', express.csrf()). You just want to find an expressive way to make it clean when the middleware will or will not be used.

like image 99
Peter Lyons Avatar answered Oct 16 '22 07:10

Peter Lyons


Since Express middleware executes in order, you could always put your statements above the csrf() statement in the code.

Like this:

app.get '/ping', (req, res) -> res.status(200).end()
app.use csrf()

Express will return before your csrf token gets set. For very small numbers of endpoints (I just have one that fits this category), I've found this to be a cleaner solution.

Also, as of this writing, the code for the above answer would look like this:

customCsrf = (req, res, next) ->
  if req?.url isnt '/ping'
    return csrf()(req, res, next)
  else
    return next()

app.use customCsrf

That extra (req, res, next) tripped me up for awhile, so hope this helps someone.

like image 35
Kevin Avatar answered Oct 16 '22 06:10

Kevin


dailyjs.com has a good article about csrf and express. It basically works like this:

use the csrf middleware:

app.configure(function() {
  // ...
  app.use(express.csrf());
  // ..
});

create a custom middleware that sets the local variable token to the csrf value:

function csrf(req, res, next) {
  res.locals.token = req.session._csrf;
  next();
}

use your custom middleware in every route you want:

app.get('/', csrf, function(req, res) {
  res.render('index');
});

in your form create a hidden field that holds the csrf value:

form(action='/contact', method='post')
  input(type='hidden', name='_csrf', value=token)
like image 1
zemirco Avatar answered Oct 16 '22 06:10

zemirco


Use the middleware at express app level adding every HTTP method to the ignored list, to ensure that the protection does not verify by default.

E.g.

const ignoredMethods = [
    'GET',
    'HEAD',
    'POST',
    'PUT',
    'DELETE',
    'OPTIONS'
]

const csrfInit = csurf({ignoredMethods, cookie: true });
app.use(csrfInit);

This will inject the csrfToken() method into each request object allowing the setup of a hidden field or consumable cookie by the application.

Then add a protected version in your as middleware to desired routes, and ignore the ones that do not require it.

E.g. Protected

const csrfProtection = csurf({ cookie: true });


router.post('/api/foo', csrfProtection, (req, res, next) => ...

E.g. Unprotected

const csrfProtection = csurf({ cookie: true });


router.post('/api/foo', (req, res, next) => ...

That worked for me.

like image 1
hexmark records Avatar answered Oct 16 '22 08:10

hexmark records