expressjs / csurf

CSRF token middleware
MIT License
2.3k stars 217 forks source link

Allow to manually verify CSRF tokens for ignored methods #47

Closed shesek closed 9 years ago

shesek commented 9 years ago

Useful for blocking specific GET endpoints from being accessed without a CSRF token. In my specific use-case, its for blocking sensitive JSON-returning endpoints to avoid cross-domain JSON hijacking.

Without exposing this functionality from inside of csurf, replicating the behavior can get quite messy.

dougwilson commented 9 years ago

I'm not sure I understand the use-case. Why can't you just put the csurf on that protected route?

var csurf = require('csurf')

// sometime later
app.use(csurf())

// later on your GET route
app.get('/protected', csurf({ignoreMethods: []}), function (req, res, next) {
  // this is csrf protected now, even though it's a GET
})
gabeio commented 9 years ago

I did not know that you could do that >.>

jonathanong commented 9 years ago

@gabeio the way i would structure my app is to split the "JSON API" endpoints into two:

var api = express();
api.get('/things', function (req, res) {
  res.json([]);
});

Then mount it in your app like so, so that csurf() is only used on non-API routes:

var app = express();

app.use('/api/v1', require('./api');

app.use(require('csurf')());

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

either way, there are many ways to filter your routes for any middleware:

var csurf = require('csurf')();

app.use(function (req, res, next) {
  if (<i don't want to do CSRF validations on these routes>) return next();
  csurf(req, res, next);
});
gabeio commented 9 years ago

wow these things I never thought of trying :+1: @ that last code block. and the second one pure genius going to fix one of my apps right now :+1: thanks!