Remove csrf protecteion on API post calls

拈花ヽ惹草 提交于 2020-01-02 04:44:07

问题


I would like to remove csrf from my Express 3.0 application as i don't need it there. I use oauth to validate clients. Is the a middleware to whitelist API urls when using express.csrf()?


回答1:


You can do that in two ways.

1.) Create a small middleware of your own to allow white list url patterns not to be blocked by csrf like;

var express = require("express");
var expressCsrf = express.csrf();
var app = express.createServer();

var customCsrf = function (req, res, next) {
    // I assume exact match, but you can use regex match here
  var csrfEnabled = true;
  var whiteList = new Array("/pattern1/param1","/pattern2/param2","/pattern3/param3");
  if (whiteList.indexOf(req.path) != -1) {
    csrfEnabled = false;
  }

  if (csrfEnabled) {
    expressCsrf(req, res, next);
  } else {
    next();
  }
}

app.use(customCsrf);
app.listen(3000);

2.) Use csrf middleware on your controllers you want to enable. For example, you want to use csrf check on profile save controller;

app.post("/profile/save", express.csrf(), function(req, res, next) {
    // put your code here
});


来源:https://stackoverflow.com/questions/22295113/remove-csrf-protecteion-on-api-post-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!