允许具有帆政策的任何人访问API

时间:2018-09-09 15:03:30

标签: javascript node.js sails.js

我正在尝试将SailsJS API与另一个节点应用程序一起使用,并不断获得403 Forbidden响应类型。

我的动作是scale/create-weight,它使用发布的数据创建数据库记录。

我将操作添加到config/policies.js中,以允许未登录用户进行访问:

//config/policies.js

module.exports.policies = {

  '*': 'is-logged-in',

  // Bypass the `is-logged-in` policy for:
  'entrance/*': true,
  'account/logout': true,
  'view-homepage-or-redirect': true,
  'deliver-contact-form-message': true,
  'scale/create-weight': true

};

这是我尝试从同一台计算机上的单独节点应用程序访问API的方式:

const querystring = require('querystring')
const http = require('http')

const postData = querystring.stringify({
  'weight' : '10',
  'units' : 'ounces',
  'userId' : '5b8c16301cee97343513e184'
});

var options = {
    host: "localhost",
    port: 1337,
    path: "/api/v1/scale/create-weight",
    method: "POST",
    headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(postData)
      }
};


const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// write data to request body
req.write(postData);
req.end();

服务器正在响应:

STATUS: 403
HEADERS: {"x-powered-by":"Sails <sailsjs.com>","content-type":"text/plain; charset=utf-8","content-length":"9","etag":"W/\"9-PatfYBLj4Um1qTm5zrukoLhNyPU\"",
"set-cookie":["sails.sid=s%3AonM7KWW6ohNoOPNiNjXy9NRFapolNavV.eZHy2P1o4WN1BvDbIWAZEsafG9RzaN1D6O%2FgaEjoLq0; Path=/; HttpOnly"],"date":"Sun, 09 Sep 2018 14:
55:58 GMT","connection":"close"}
BODY: Forbidde
BODY: n
No more data in response.

我该怎么做才能允许外部应用使用API​​?

1 个答案:

答案 0 :(得分:0)

该问题归因于csrf安全策略。尽管完全关闭设置不是很好,但是您可以在config/routes.js文件中按路由进行管理。

我更新了路线,它可行:

'POST /api/v1/scale/create-weight': {
  action: 'scale/create-weight',
  csrf: false
},

我最终将实施API密钥/ API秘密安全策略,以便使用该API的第三方可以进行这种身份验证。