How to get CSRF from django in a separate React App

Viewed 1233

After researching CSRF tokens and django, it's clear that the React app has to be rendered via django in order to retrieve the CSRF token normally (i.e. injected into the DOM)

The only reason I take issue with this I know instagram is using Django and React for their web app; I find it highly unlikely it's being rendered -- at least in a traditional way -- by django.

I realize it will be difficult to find an answer to how they are handling it, but perhaps someone knows a way of doing this without rendering a very large enterprise-level react app with django.

To give some perspective, our react application is in a separate repo & directory on a different subdomain to our django powered API.

We've looked for advice in every area I can think of and have yet to find a proper solution, so I appreciate any feedback you can give

3 Answers

I used get_token from django.views.decorators.csrf to generate a csrf token.

my django code in views.py:

from django.http import JsonResponse
from django.views.decorators.csrf import get_token

def get_csrf(request):
    return JsonResponse({"token":get_token(request)})

I called this view function in react native to get a csrf token: my reactnative code:

React.useEffect(()=>{ 
 fetch("api endpoint",{
 method:"GET",
 headers:{
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
 }).then((response)=>response.json())
.then((json)=>{
    //save your csrf-cookie (i use secure store to save it) 
   })
},[]);

You can generate a csrf token like this:

from django.middleware.csrf import get_token
csrf_token = get_token(request)

You can store the csrf token in a cookie, using ensure_csrf_cookie if necessary, and adding the header to XHR requests:

import Cookies from 'js-cookie';

Request.post(url)
    .set('X-CSRFToken', Cookies.get('csrftoken'))
    .send(data)
Related