Search code examples
djangodjango-csrf

How and where to generate a CSRF token for to make requests to a Django app through a REST API?


I have a Django view login that allows me to get a session for a user using POST data from an Android app. It works because I set the @csrf_exempt decorator, but I'll need the CSRF token for subsequent requests.

How can I get the CSRF token? Should it be generated on my Android app or on the Django app? Then how do I add it to my requests?

from django.contrib import auth
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser


class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
            content = JSONRenderer().render(data)
            kwargs['content_type'] = 'application/json'
            super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
def login(request, *args, **kwargs):

    # Login
    username = request.POST.get('username')
    password = request.POST.get('password')

    user = auth.authenticate(username=username, password=password)

    if user is not None:
            if user.is_active:
                    auth.login(request, user)
                    return JSONResponse({'success': 1, 'user_id': user.id})
            return JSONResponse({'success': 0, 'msg': 'User is not active'})
    return JSONResponse({'success': 0, 'msg': 'Wrong username and/or password'})

Solution

  • I had to add the decorator from django.views.decorators.csrf import ensure_csrf_cookie to my function to make it returns a CSRF token.