sailsjs的CSRF问题

我在sails.jscsrf上遇到了一些麻烦,我激活它,并创build像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) 

有人可以帮我find解决办法? 我认为这是一件简单的事情,我只是不知道这是什么“简单的事情”

       

网上收集的解决方案 "sailsjs的CSRF问题"

如果您的应用程序处于生产模式,则会根据默认的forbidden.js文件将“csrf”不匹配响应掩盖为“Forbidden”。

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

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

请注意,我突出显示了导致这种情况的行,这是您将添加数据检查的位置===“CSRF不匹配”,并避免将数据更改为未定义,或者更改您希望的数据。

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

 $http.get($scope.baseUrl + '/csrfToken') .success(function(csrfObj) { csrfToken = csrfObj._csrf; }); $http.post('/chat/addconv/',{user:$scope.chatUser,message: $scope.chatMessage, _csrf:csrfToken}); 

你可以为此创build一个简单的指令

 (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; } })(); 

然后使用它的forms

 <form csrf name="form">