sailsjs的CSRF问题

时间:2014-07-06 23:19:00

标签: node.js sails.js csrf

我在使用sails.js的csrf时遇到了一些麻烦,我在sailsjs文档中创建了隐藏字段,但是当我提交表单时,我总是得到这样的响应:

Error: Forbidden
    at Object.exports.error (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:62:13)
    at createToken (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/middleware/csrf.js:82:55)
    at /Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/node_modules/connect/lib/middleware/csrf.js:48:24
    at routes.before./* (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/lib/hooks/csrf/index.js:26:28)
    at _bind.enhancedFn (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/lib/router/bind.js:375:4)
    at callbacks (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
    at param (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
    at pass (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
    at nextRoute (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
    at callbacks (/Users/matheus/Development/javascript/activity_overlord/node_modules/sails/node_modules/express/lib/router/index.js:167:11)

有人可以帮我找到解决方案吗?我觉得这很简单,我只是不知道这是什么"简单的事情"

3 个答案:

答案 0 :(得分:2)

如果您的应用处于生产模式,则会根据默认的forbidden.js文件使用“Forbidden”屏蔽csrf不匹配响应。

你可以通过创建文件“api / responses / forbidden.js”并将其内容复制到其中来覆盖它

https://github.com/balderdashy/sails/blob/master/lib/hooks/responses/defaults/forbidden.js#L35

请注意,我突出显示导致此行的行,您可以在此处添加数据检查==='CSRF Mismatch',并避免将数据更改为未定义,或者根据需要更改响应。

答案 1 :(得分:1)

首先,您需要通过调用webservice(/ csrfToken)来获取CSRF令牌。作为回应,您将获得一个令牌。您需要在服务器的所有后续请求中发送该令牌。

a.*(?i)

答案 2 :(得分:0)

您可以为此

创建一个简单的指令
(function() {
  'use strict';

  angular
      .module('app')
      .directive('csrf', csrf);

  csrf.$inject = ['$http'];

  function csrf($http) {
    var directive = {
      restrict: 'A',
      link: function(scope, element, attr) {
        $http({method: 'GET', url: '/csrfToken', cache: true}).then(function(result) {
          try {
            $http.defaults.headers.post['X-CSRF-Token'] = result.data._csrf;
          } catch(e) {
            // do something
          }
        });
      }
    };

    return directive;
  }
})();

然后使用表格

<form csrf name="form">