在响应本机中获取csrf令牌 [英] get csrf token in react native

查看:78
本文介绍了在响应本机中获取csrf令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了django服务器来管理我的数据,然后我有了桌面react应用程序,可以在其中创建新用户/登录/发布数据,它可以完美运行,它基于csrf令牌验证,因此没有问题.但是我也有react-native应用程序,该应用程序应该允许用户登录,并获取属于他的GET数据.这是一个问题,如何在React Native中获得CSRF令牌?在桌面应用中,它或多或少看起来像这样,但是我不知道如何登录react native,因为我不能简单地使用csrf令牌获取Cookie.

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

推荐答案

有两个选项:

  • 如果django应用程序API仅服务于移动应用程序(本机反应),则对于该应用程序使用的那些API,您根本不需要CSRF保护.这是因为CSRF可以防止浏览器(而不是应用程序)中的伪造.

  • 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.

但是,如果您的api也用在浏览器中,那么您应该创建一个端点,以使用返回json中csrf令牌的Django视图来专门获取csrf令牌(GET/api/csrftoken).

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.

这篇关于在响应本机中获取csrf令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆