[Django]-How do I generate a Django CSRF key for my iPhone and Android apps that want to send a POST request?

6👍

✅

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.

1👍

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

Leave a comment