Jac*_*cki 2 django csrf reactjs react-native
我已经构建了 django 服务器来管理我的数据,然后我有桌面 React 应用程序,我可以在其中创建新用户/登录/发布数据,它工作完美,它基于 csrf 令牌验证,没有问题。不过,我还有反应本机应用程序,它应该让用户登录并获取属于他的数据。这里有一个问题,如何在 React Native 中获取 CSRF 令牌?在桌面应用程序中,它看起来或多或少像这样,但我不知道如何登录反应本机,因为我不能简单地使用 csrf 令牌获取 Cookie。
componentDidMount() {
const csrfToken = Cookies.get('csrftoken')
this.setState({csrfToken})
}
loginHandler = login_data => {
this.setState({
user: login_data.user,
password: login_data.password
}, () => {
const auth = {
"username": this.state.user,
"password": this.state.password
}
fetch("http://localhost:8000/data/", {
method: 'POST',
credentials: 'include',
headers: {
"X-CSRFToken": this.state.csrfToken,
},
body: JSON.stringify(auth)
})
.then((res) => res.json())
.then(resp => console.log(resp))
.then(() => this.getData())
.catch(() => this.setState({
user: "",
passowrd: ""
}))
})
};
Run Code Online (Sandbox Code Playgroud)
有两种选择:
如果您的 django 应用程序 API 仅服务移动应用程序(本机反应),那么您根本不需要应用程序使用的这些 API 的 CSRF 保护。这是因为 CSRF 可以防止浏览器中的伪造,而不是应用程序中的伪造。
但是,如果您的 api 也在浏览器中使用,那么您应该创建一个端点,以使用以 json 形式返回 csrf 令牌的 Django 视图专门获取 csrf 令牌 (GET /api/csrftoken)。
| 归档时间: |
|
| 查看次数: |
8771 次 |
| 最近记录: |