Disable csrf validation for some requests on Express

前端 未结 3 1980
忘了有多久
忘了有多久 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: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.

提交回复
热议问题