sails.js如何让_csrf在vuejs中使用

问题描述 投票:0回答:2

我正在使用sails.js来构建REST API。我想使用sails.js的第一个内置模板。 sails.js template choice

我遇到身份验证问题。我不能使用post man登录或登录。我搜索了一下,我能够在帆中获得_csrf令牌

<form>
  <input type="hidden" name="_csrf" value="<%= _csrf %>" />
</form>

但是我找不到任何路径可以将令牌作为json传递给我,以便我可以从vue访问它。有点像GET : localhost:1337/api/token

{ _csrf: 'ajg4JD(JGdajhLJALHDa' }

有人可以帮助我走上正轨。我一直在寻找一段时间。

node.js sails.js
2个回答
1
投票

For frontend

在您的前端,您可以访问由Sails-window.SAILS_LOCALS._csrf插入的全局对象上的CSRF。

For testing

在你的config/routes.js,你将不得不添加这个:

'GET /.temporary/csrf/token/for/tests': { action: 'security/grant-csrf-token' },

不要让它去生产。建议的方法是仅在自动化测试期间公开此路由。这里有一些关于在Sails.js中测试的信息 - https://sailsjs.com/documentation/concepts/testing - 这是我的lifecycle.test.js - https://gist.github.com/Noitidart/63df651dc76812da6cb3bfe1ce4e9e0e - 你看我只为我的测试公开这条路线,所以我的制作不会得到这个。不建议使用Postman测试您的端点,因为这些测试是短暂的,您的测试工作现在已经完成。但是如果你编写单元/集成测试,那么工作测试将永远存在。


0
投票

如果您使用的是Sails v1

// config/security.js
module.exports.security = {
    csrf: true,
};

// config/routes.js
'GET /csrfToken': 'SomeController.grantCsrfToken', 

// api/controllers/SomeController.js
module.exports = {
 grantCsrfToken: function (req, res /*, next */) {
    // Don't grant CSRF tokens over sockets.
    if (req.isSocket) {
      if (process.env.NODE_ENV === 'production') {
        return res.notFound();
      }
      return res.badRequest(new Error('Cannot access CSRF token via socket request.  Instead, send an HTTP request (i.e. XHR) to this endpoint.'));
    }
    // Send the CSRF token wrapped in an object.
    return res.json({
      _csrf: res.locals._csrf
    });
  },
}

// assets/js/some_filename.js
function send_some_post_request(extra_params) {
  $.get("/csrfToken", function (data, jwres) {
    if (jwres != 'success') { return false; }
    msg = {
      extra_params: extra_params,
      _csrf: data._csrf
    };
    $.post("doStuff", msg, function(data, status){
    });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.