【发布时间】: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