get csrf token in react native

廉价感情. 提交于 2021-01-29 09:48:56

问题


I have built django server to manage my data, then I have desktop react app where I can create new users/login/post data, it works flawless, It is based on csrf token verification and there is no problem with that. However I have also react-native app which is supposed to let user log in, and GET data which belongs to him. And here is question, how to get CSRF token in react native? In desktop app it looks more or less like this but I have no idea how to login in react native as I can't simply get Cookie with csrf token.

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: ""
        }))
    })
  };

回答1:


There are two options:

  • If your django app API only services mobile apps (react native) then you don't need CSRF protection at all for those APIs used by the app. That's because CSRF protects from forgery in browsers, not in apps.

  • But if your api is also used in a browser, then you should create an endpoint to specifically fetch the csrf token (GET /api/csrftoken) with a Django view that returns the csrf token in json.



来源:https://stackoverflow.com/questions/59628605/get-csrf-token-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!