Reputation: 271774
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.
But what if my iPhone app (a client) wants to send a POST request to my web service? How do I give my iPhone app a CSRF token that it can temporarily use?
Upvotes: 3
Views: 1848
Reputation: 306
You can set up a JsonResponse with a unique key such as this in your view.
# 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
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.
I'm using Django 3.dev and Python3
Upvotes: 1
Reputation: 6182
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. The whole point of CSRF tokens is that the server has to generate them.
Is your goal to authenticate the iPhone app so that other apps can't POST to your 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.
Upvotes: 6