【问题标题】:Axios + Ionic React + Sails: _csrf token 403 ForbiddenAxios + Ionic React + Sails:_csrf token 403 Forbidden
【发布时间】:2020-01-29 03:41:04
【问题描述】:

我正在开发一个使用 Sails.js 的 API 和一个使用 Ionic-React 的用户应用程序。在页面加载时,我发出 axios 请求以获取 _csrf 令牌。当我从登录表单向sails 提交数据时,我总是收到403 Forbidden 响应。我在sails 中禁用了csrf (config/security.js),然后我可以检索响应。我在标头中发送令牌。

我也在尝试获取会话 cookie,但它不起作用我认为这可能是服务器拒绝请求的原因。

离子应用:

componentDidMount(this: this) {
axios.get('http://localhost:1337/api/v1/security/grant-csrf-token')
  .then(response => {
    const _csrf = response.data._csrf
    this.setState({
      form: {
        ...this.state.form,
        _csrf: _csrf,
      }})
  });
}

提交时:

const { emailAddress, password, _csrf } = this.state.form;
const config= {
  data: {
    "emailAddress": emailAddress,
    "password": password,
  },
  headers: {
    "x-csrf-token": _csrf
  },
  withCredentials: true,
  jar:cookieJar,
};

axios.post('http://localhost:1337/api/v1/users/authenticate', null, config)
.then(res => {
  console.log(res);
})
.catch(err => {
  console.log(err);
})};

关于 Chrome DevTools 网络响应:

在 Postman 上,同样的请求有效,我得到 200 的用户数据,并且请求确实包含sails.sid cookie。

我不想禁用 csrf 保护,那不是解决方案。是我缺少的sails.sid cookie吗?

【问题讨论】:

  • 根据我使用 axios 和风帆的经验。您需要将 csrf 令牌作为请求中的标头发送。所以在sails security.js 文件中,将allowCredentials 设置为true。然后在你的 axios 帖子中添加withCredentials : true。然后将 csrf 添加为标题。像axios.defaults.headers.common['X-CSRF-TOKEN'] = _csrf 这样的东西应该适用于你的情况。

标签: ionic-framework cookies axios sails.js csrf


【解决方案1】:

我正在使用这个,

axios({
                method: 'post',
                crossdomain: true,
                url: apiFormUrl,
                data: formData,
                headers: {
                    "Content-Type": "multipart/form-data",
                    "Authorization": access_token
                }
            })
                .then

它可以工作

【讨论】:

  • 我刚试了一下,用这种方式发送请求对我不起作用
  • 我按照您的要求发送了请求,只是将“跨域”更改为“withCredentials”。 “crossdomain”参数在 Ionic-TypeScript 上引发异常。在标题上,我尝试了 Sailsjs 文档中的“授权”和“x-csrf-token”。我仍然收到 403 - Forbidden 响应。
猜你喜欢
  • 2019-10-17
  • 2020-06-21
  • 2020-07-22
  • 2015-11-16
  • 2017-09-21
  • 2015-12-05
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多