tytho tytho - 2 months ago 16x
Node.js Question

How to test endpoints protected by csrf in node.js/express

I have implemented csrf (cross-site request forgery) protection in an express like so:

app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());

This works great. Angularjs utilized the csrf token in all requests made through the $http service. The requests that I make through my angular app work great.

My problem is testing these api endpoints. I'm using mocha to run my automated tests and the request module to test my api endpoints. When I make a request to an endpoint that utilizes csrf (POST, PUT, DELETE, etc.) using the request module, it fails, even though it correctly utilizes cookies and such.

Has anybody else come up with a solution to this? Does anyone need more information?

Example of test:

function testLogin(done) {
method: 'POST',
url: baseUrl + '/api/login',
json: {
email: 'myemail@email.com',
password: 'mypassword'
}, function (err, res, body) {
// do stuff to validate returned data
// the server spits back a 'FORBIDDEN' string,
// which obviously will not pass my validation
// criteria


The trick is that you need to wrap your POST test inside a GET and parse the necessary CSRF token from the cookie. First, this assumes you create an Angular-compatible CSRF cookie like this:

.use(function (req, res, next) {
  res.cookie('XSRF-TOKEN', req.session._csrf);
  res.locals.csrftoken = req.session._csrf;

Then, your test could look like this:

describe('Authenticated Jade tests', function () {

  before(function (done) {
    [Set up an authenticated user here]

  var validPaths = ['/help', '/products'];

  async.each(validPaths, function (path, callback) {
    it('should confirm that ' + path + ' serves HTML and is only available when logged in', function (done) {
      request.get('' + process.env.PORT + path, function (err, res, body) {
        expect(body).to.be('Moved Temporarily. Redirecting to /login');

        var csrftoken = unescape(/XSRF-TOKEN=(.*?);/.exec(res.headers['set-cookie'])[1]);
        var authAttributes = { _csrf: csrftoken, email: userAttributes.email, password: 'password' };

        request.post('' + process.env.PORT + '/login', { body: authAttributes, json: true }, function (err, res) {

          request.get('' + process.env.PORT + path, function (err, res, body) {

            request.get('' + process.env.PORT + '/bye', function () {


The idea is to actually login and use post the CSRF token you're getting from the cookie. Note that you need the following at the top of the mocha test file:

var request = require('request').defaults({jar: true, followRedirect: false});