2

How to pass CSRF token between Django applications by reading it from request using urllib.

I am having two servers running with Django applications, based on URL need to send request to other server and give the response back.

Django middelware either returns None or Response.
In case of None: it processes request on same server.
In case of Response: it sends the response bake to client and bypassing request to same server.

Say I have two servers "S1" and "S2", and for URL ("/user/1/profile") I have to send request to "S2".

I am doing request cloning in django middleware which checks the matching URL and makes https request(using urllib) with all cookies and headers to "S2" server and sending response back by converting it from urllib-response to django-response.

With "GET" requests its working fine, but I am getting "403 CSRF" with "POST" requests.

Any suggestions what I am missing here.

Raghvendra Parashar
  • 3,883
  • 1
  • 23
  • 36

1 Answers1

4

As I understand you are building a REST api.

The DjangoCSRF Token is browser dedicated. You can disable the DjangoCsrf Protection by adding the csrf_exempt decorator

From the docs:

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

But you should consider using the Django Rest Framework And it's Authentication Methods for improved security.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • I've been finding it hard to find info on this. So, if I am understanding right, csrf is only something you can do if you also have an authentication mechanism? I have two backends that I want communicating with each other and not sure where I am supposed to add the `csrf_token`. – Akaisteph7 Sep 01 '23 at 21:47