简体   繁体   English

使用REST API时如何获取CSRF令牌并将其包含在标头中

[英]How to get and include the CSRF token in the header when working with REST API

我正在使用python Django创建REST API。客户端是在react中开发的,并且是独立的应用程序。我使用axios来触发http请求。我需要在每个post请求中传递CSRF令牌,但不是能够从浏览器获取CSRF令牌。

How to pass your CSRF when doing Ajax request? 进行Ajax请求时如何通过CSRF?

First, make sure you have the django.middleware.csrf.CsrfViewMiddleware in your middlewares list in your settings file. 首先,确保设置文件中的中间件列表中有django.middleware.csrf.CsrfViewMiddleware。 This middleware sets the CSRF_TOKEN in the cookie so you can retrieve it for your ajax request. 该中间件在cookie中设置CSRF_TOKEN,以便您可以针对ajax请求检索它。

Second, Django can now store the CSRF in the session. 其次,Django现在可以在会话中存储CSRF。 However, in your particular case you don't want the CSRF_TOKEN in the session. 但是,在特定情况下,您不需要会话中的CSRF_TOKEN。 Make sure you have CSRF_USE_SESSIONS = False (which is the default) to have the CSRF in the cookie. 确保您具有CSRF_USE_SESSIONS = False(这是默认值),以将CSRF包含在cookie中。

If you check the cookies you should now have a CSRF_TOKEN in there. 如果您检查Cookie,现在应该在那里有一个CSRF_TOKEN。 You can add it dynamically to your ajax request IF you are using jquery with the following code. 如果您使用带有以下代码的jquery,则可以将其动态添加到您的ajax请求中。

https://docs.djangoproject.com/en/1.11/ref/csrf/#setting-the-token-on-the-ajax-request https://docs.djangoproject.com/zh-CN/1.11/ref/csrf/#setting-the-token-on-the-ajax-request

I'm saying IF you use Jquery because you are using React, which doesn't need Jquery to do Ajax request, it's up to you how you do them. 我说的是,如果您使用Jquery是因为您使用的是React,则不需要Jquery来执行Ajax请求,这取决于您如何执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Django Rest 框架在 Header 中包含令牌 - How to include Token in Header using Django Rest Framework 如何在iOS中获取CSRF令牌? - How to get CSRF token in iOS? “rest_framework CSRF 令牌失败”,但它已在请求 header 中设置为“X-CSRF-Token” - “rest_framework CSRF token failed” but it's already set in the request header as “X-CSRF-Token” @csrf_exempt不适用于REST API - @csrf_exempt not working for rest api 当CSRF_USE_SESSIONS为True时,如何从移动应用程序获取CSRF令牌? (Django 1.11) - How to get CSRF token from mobile apps when CSRF_USE_SESSIONS is True ? (Django 1.11) 如何以及在何处生成CSRF令牌,以通过REST API向Django应用发出请求? - How and where to generate a CSRF token for to make requests to a Django app through a REST API? Django Rest 框架说 CSRF 验证失败,尽管 CSRF 令牌包含在 axios POST Z0995EFZ640F39E - Django Rest Framework says CSRF verification failed despite CSRF token is included in axios POST header 在django中测试POST端点时如何包含csrf令牌? - how do you include a csrf token when testing a POST endpoint in django? 带有jwt身份验证的django rest api要求使用csrf令牌 - django rest api with jwt authentication is asking for csrf token Django rest-api:邮递员看不到 CSRF 令牌 - Django rest-api: Postman can't see CSRF token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM