3

I'm setting up Stripe to work with my sails.js server, and in order to use Stripe's webhooks, I need to disable CSRF for the URLs I provide to Stripe.

Is it possible to make certain URLs exempt from CSRF POST requirements in sails.js? The only configuration I can find for CSRF is to turn it on globally, and looking through the source code for the csrf hook (https://github.com/balderdashy/sails/blob/master/lib/hooks/csrf/index.js) it looks like if I try to provide a custom object, it just gets replaced with the global settings anyway.

Thanks

Armel Larcier
  • 15,747
  • 7
  • 68
  • 89
Murcho
  • 105
  • 6
  • possibly related (expressjs): https://stackoverflow.com/questions/13516898/disable-csrf-validation-for-some-requests-on-express also related: https://gist.github.com/mikermcneil/5737561#sailsconfigcontrollercsrf – timh Mar 04 '15 at 06:36
  • @timh I had looked at that, and you can provide middleware like that in sails.js via policies, however the existing csrf policy would run before the custom one. – Murcho Mar 04 '15 at 20:50

2 Answers2

7

So after reading through the csrf hook linked in the question a bit more I managed to work it out.

As of v0.11.0 :

If you try to provide an object with settings in the csrf.js config file, the hook simply overwrites them with "default on" for all settings. The csrf object ends up looking like this

{
  grantTokenViaAjax: true,
  protectionEnabled: true,
  origin: '-',
  routesDisabled: '-'
}

In order to add route exemptions to the object, you need to do it after this has been set up, so I did this in config/bootstrap.js. So to add the route "http://yourhost.com/webhooks/testhook/" :

// In bootstrap.js
sails.config.csrf.routesDisabled = "/webhooks/testhook";

If you want to add more than one hook, you add them in the same string, comma delimited:

// In bootstrap.js
sails.config.csrf.routesDisabled = "/webhooks/testhook,/webhooks/anotherhook";
Murcho
  • 105
  • 6
6

So Murcho's solution is working but actually, sails v0.11 has a config file just for that :

In config/csrf.js, after the line where you activate csrf protection lies this comments block :

/****************************************************************************
*                                                                           *
* You may also specify more fine-grained settings for CSRF, including the   *
* domains which are allowed to request the CSRF token via AJAX. These       *
* settings override the general CORS settings in your config/cors.js file.  *
*                                                                           *
****************************************************************************/

// module.exports.csrf = {
//    grantTokenViaAjax: true,
//    origin: ''
// }

You just need to add a config object there to extend the defaults :

module.exports.csrf = {
  "routesDisabled": "/webhooks/testhook,/webhooks/anotherhook"
}
Armel Larcier
  • 15,747
  • 7
  • 68
  • 89