如何在Django RESTful API和React中使用csrf_token? [英] How to use csrf_token in Django RESTful API and React?

查看:366
本文介绍了如何在Django RESTful API和React中使用csrf_token?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前在 Django 中有经验。如果在 Django 模板中添加行 {csrf_token} ,则 Django 处理 csrf_token 的功能。但是,当我尝试使用 Django REST Framework 开发API时,就会遇到麻烦。如何在 API (后端,使用 Django开发的后端)中添加和处理 csrf_token 之类的功能REST Framework )和 React Native / React JS (前端),例如Django模板?

I have previous experience in Django. If add line {csrf_token} in Django templates then Django handles the functionalities of csrf_token. But when I am trying to develop an API using Django REST Framework then I get stuck. How can I add and handle functionalities like csrf_token in API (back end, developed using Django REST Framework) and React Native/React JS (front end) like Django templates?

推荐答案

第一步是获取可以从Django csrftoken cookie中检索的CSRF令牌。

The first step is to get CSRF token which can be retrieved from the Django csrftoken cookie.

现在从 Django文档,您可以找到使用此方法从Cookie中获取csrf令牌的方法简单的JavaScript函数:

Now from the Django docs you can find out how to get the csrf token from the cookie by using this simple JavaScript function:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

现在,您可以通过调用 getCookie('csrftoken')函数

Now, you can retrieve the CSRF token by calling the getCookie('csrftoken') function

var csrftoken = getCookie('csrftoken');

接下来,您可以通过将检索到的令牌分配给fetch()发送请求时使用此csrf令牌X-CSRFToken标头。

Next you can use this csrf token when sending a request with fetch() by assigning the retrieved token to the X-CSRFToken header.

  fetch(url, {
    credentials: 'include',
    method: 'POST',
    mode: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRFToken': csrftoken
    },
    body: {}
   })
  }

以React形式呈现CSRF令牌:

如果您正在使用React来呈现表单而不是Django模板,您还需要呈现csrf令牌,因为Django标签 {%csrf_token%} 在客户端不可用,因此您需要创建一个使用 getCookie()函数检索令牌并以任何形式呈现的更高阶组件。

If you are using React to render forms instead of Django templates you also need to render the csrf token because the Django tag { % csrf_token % } is not available at the client side so you need to create a higher order component that retrieves the token using the getCookie() function and render it in any form.

让我们在 csrftoken.js 文件。

import React from 'react';

var csrftoken = getCookie('csrftoken');

const CSRFToken = () => {
    return (
        <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />
    );
};
export default CSRFToken;

然后,您可以简单地将其导入并在表单中调用

Then you can simply import it and call it inside your form

import React, { Component , PropTypes} from 'react';

import CSRFToken from './csrftoken';


class aForm extends Component {
    render() {

        return (
                 <form action="/endpoint" method="post">
                        <CSRFToken />
                        <button type="submit">Send</button>
                 </form>
        );
    }
}

export default aForm;

Django CSRF Coo​​kie

React动态地渲染组件,这就是为什么如果您使用React渲染表单,Django可能无法设置CSRF令牌cookie。 Django文档是这样说的:

React renders components dynamically that's why Django might not be able to set a CSRF token cookie if you are rendering your form with React. This how Django docs says about that:


如果您的视图未呈现包含csrftoken
模板标签的模板,则Django可能未设置CSRF令牌cookie。在将表单动态添加到页面的情况下,这通常是
。为了解决
的这种情况,Django提供了一个视图装饰器来强制设置cookie的
设置:surecsrf_cookie()。

If your view is not rendering a template containing the csrftoken template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensurecsrf_cookie().



<为了解决这个问题,Django提供了您需要添加到视图函数中的surecsrfcookie装饰器。例如:

To solve this issue Django provides the ensurecsrfcookie decorator that you need to add to your view function. For example:

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def myview(request):

这篇关于如何在Django RESTful API和React中使用csrf_token?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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