Node.js有条件地使用csurf和express 4

mar*_*hro 6 csrf node.js express-4

我尝试在我的快递应用中的几条路线上使用csurf.这是方法:

var express       = require('express');
var session       = require('express-session');
var csrf          = require('csurf');

// some more stuff

var csrfExclusion = ['/myApi','/unsecure'];

var app   = express();

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
  }
});

app.use(conditionalCSRF);
Run Code Online (Sandbox Code Playgroud)

甚至试过:

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf(req, res, next);
    next();
  }
});
Run Code Online (Sandbox Code Playgroud)

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
    next();
  }
});
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:对象#没有方法'csrfToken'

我怎样才能有条件地使用csurf.该文档仅提供在Express应用程序中的所有路径上使用它的信息

app.use(csrf());
Run Code Online (Sandbox Code Playgroud)

但这不是我想要的,我想排除一些路线......

亲切的......马丁

更新:

最后它有效.我做了以下事情:

app.use(function(req, res, next){
  if (csrfExclusion.indexOf(req.path) !== -1) {
  next();
}
  else {
  csrf()(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)

这有条件地添加了csrf中间件.但我真的认为这样称呼它有点奇怪:

csrf()(req, res, next);
Run Code Online (Sandbox Code Playgroud)

我甚至没有得到语法......

Ben*_*une 6

根据这个你需要将它分成两个路由器,一个使用csurf而另一个不使用.然后,您将中间件应用于路由器而不是应用程序.

var routes = express.Router();
var csrfExcludedRoutes = express.Router();

routes.use(csrf());

routes.get('/', function(req, res) {
    //has req.csrfToken()
});

csrfExcludedRoutes.get('/myApi', function(req, res) {
    //doesn't have req.csrfToken()
});
Run Code Online (Sandbox Code Playgroud)

  • 我无法让这个建议的解决方案起作用,但原始海报在他的更新中描述的解决方案做到了。 (2认同)