【问题标题】:Sailsjs + vuejs + axios + CSRF tokensSailsjs + vuejs + axios + CSRF 代币
【发布时间】:2018-11-06 13:35:02
【问题描述】:

我有些东西不明白。总是得到一个错误 403。我在前端(vue.js)中有一个代码,这里我从 Sails.js 得到一个令牌 _csrf,没关系。

axios.get('http://localhost:1337/csrfToken')
        .then(response => {

            this.$store.commit('csrf_update', response.data._csrf);
            console.log("_csrf===",response.data._csrf);
            axios.defaults.headers.post['X-CSRF-Token'] = response.data._csrf;
        })

我有一个后端sails.js,在security.js 中设置

cors: {
 allRoutes: true,
 allowOrigins: 'http://localhost:8080',
 allowCredentials: false,
 allowRequestMethods:'GET, POST',
 allowRequestHeaders:'content-type, X-CSRF-Token'}, csrf: true

我有一个像 _csrf: lM8avM1X-KvKz9v2zLnbQZFf8lKOThX9Llb4 这样的令牌 而且我在请求时遇到错误 403。

axios.post('http://localhost:1337/login', form)
    .then(response => {
        this.$router.push('/kabinet');
    }).catch(error => { console.log(error); });

list 403

这是我的标题

headers

怎么了?

【问题讨论】:

    标签: vue.js sails.js axios csrf http-status-code-403


    【解决方案1】:

    所以,一切都非常简单。 在(sails.js)文件security.js中将allowCredentials: false更改为allowCredentials: true,并在前端(vue.js)中更改axion,像这样添加参数withCredentials: true

    axios.get('http://localhost:1337/csrfToken',{ 
    withCredentials: true
    }).then(response => {
                console.log("_csrf===",response.data._csrf);
                axios.defaults.headers.post['X-CSRF-Token'] = response.data._csrf;
    })
    

    并且在所有 axios 请求中必须是withCredentials: true

    【讨论】:

      【解决方案2】:

      Sails 在 config>security 文件中有一个名为 csrf 的属性。如果将其设置为 true,则只需添加

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

      到您的表格或在您需要的地方。

      我正在使用 Sails 1.0.2,它运行良好。

      【讨论】:

        【解决方案3】:

        在 axios 请求的 headers 中添加:

        “x-csrf-token”:window.SAILS_LOCALS._csrf

        【讨论】:

          猜你喜欢
          • 2018-05-02
          • 2012-11-25
          • 1970-01-01
          • 1970-01-01
          • 2020-12-04
          • 2014-05-29
          • 2012-07-02
          • 1970-01-01
          • 2019-03-31
          相关资源
          最近更新 更多