Disable csrf validation for some requests on Express

前端 未结 3 1961
忘了有多久
忘了有多久 2020-12-23 23:06

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 i

相关标签:
3条回答
  • 2020-12-23 23:49

    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.

    0 讨论(0)
  • 2020-12-23 23:51

    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.

    0 讨论(0)
  • 2020-12-23 23:59

    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)
    
    0 讨论(0)
提交回复
热议问题