[英]How do I generate a Django CSRF key for my iPhone and Android apps that want to send a POST request?
Here's the thing: 这是东西:
Right now, on my website template, there is {% csrf_token %} that allows my website to send a POST request of a form. 现在,在我的网站模板上,有{%csrf_token%}允许我的网站发送表单的POST请求。
But what if my iPhone app (a client) wants to send a POST request to my web service? 但是,如果我的iPhone应用程序(客户端)想要向我的Web服务发送POST请求,该怎么办? How do I give my iPhone app a CSRF token that it can temporarily use? 如何给我的iPhone应用程序一个可以临时使用的CSRF令牌?
Is your goal to re-use an existing form? 您的目标是重用现有表格吗? if so, iPhone app should GET the page with the form and then POST using the CSRF token. 如果是这样,iPhone应用程序应使用表单获取页面,然后使用CSRF令牌进行POST。 The whole point of CSRF tokens is that the server has to generate them. CSRF令牌的全部要点是服务器必须生成它们。
Is your goal to authenticate the iPhone app so that other apps can't POST to your API? 您的目标是对iPhone应用程序进行身份验证,以使其他应用程序无法发布到您的API吗? That is a can of worms, since any secret that you give your iPhone app can be read by anybody who has downloaded the app. 那是蠕虫的罐头,因为您下载iPhone应用程序的任何秘密都可以被下载该应用程序的任何人读取。
You can set up a JsonResponse with a unique key such as this in your view. 您可以在视图中使用诸如此类的唯一密钥设置JsonResponse。
# Add in header
from django.http import JsonResponse
from django.middleware.csrf import get_token
... ...
Call the following method in your views.py with a GET method and a 'secret' query string 在您的views.py中使用GET方法和“秘密”查询字符串调用以下方法
def code(request):
if(request.method == 'GET' and request.GET.get('secret', False) == 'CHANGE_ME'):
token = get_token(request)
return JsonResponse({'token': token, 'success': 'true'})
else:
return JsonResponse({'error': 'true', 'msg': 'Invalid secret'})
Once you get the CSRF then you can submit your POST method with the information you need. 获得CSRF后,您可以提交包含所需信息的POST方法。
I'm using Django 3.dev and Python3 我正在使用Django 3.dev和Python3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.