2

I am using React with Django, most of the client server interaction is being done through the API using Django Rest Framework. I created a standard app called mail, it has a standard view which accepts a POST request with csrf_exempt and login_required decorators on it. However whenever making an ajax call through Axios it always gives me a 403 Invalid CSRF Token error - CSRF Cookie not specified.

views.py

from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt

@login_required
@csrf_exempt
def testmail(request):
    if request.method=="POST":
        EmailQueue.objects.create(subject='TEST EMAIL BROTHER', body=render_to_string('nordalmail/testmail.html'), to_email=request.user.email, from_email=settings.FROM_EMAIL, send_now=True)
        return HttpResponse("CHECK ADMIN")
    if request.method == "GET":
        return render(request, "nordalmail/test-mail.html") 

React Component

import axios from 'axios';                                                                                                                                                                                                                    
import {createMessage, returnErrors} from './messages.js';
import {tokenConfig} from './auth.js';

// Tokenconfig simply gets the Authorization Token and sends it as a Header value 

export const sendTestMail = () => (loggedUserEmail, getState) => {
    axios
        .post('http://alice:55403/nordalmail/', tokenConfig(getState))
        .then(res => {
            createMessage("A test email has been sent to your registered email address!",
            "Email Sent");
        })  
        .catch(err => {
            returnErrors("Something went wrong while sending your email, website administrator has been notified of this incidence!", "Error");
        }); 
}

Here's the Request I send

Request URL: http://alice:55403/nordalmail/
Request Method: POST
Status Code: 403 Forbidden
Remote Address: 127.0.0.1:55403
Referrer Policy: no-referrer-when-downgrade
headers: {"headers":{"Content-Type":"application/json","Authorization":"Token 35a7aa30b26ebb1c269c6cca0cd323c07e028171aa268b61d0dfc41871f93de6"}}

I am using brave browser so I don't really know how to get the raw headers. I can vouch for the validity of this Authorization Token as it does work on other proper API endpionts.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Sahil
  • 1,387
  • 14
  • 41
  • try django-cors-headers instead. – Kanishk Tanwar Mar 06 '20 at 06:36
  • I already am using them. That's how React is able to make calls to the Django server. – Sahil Mar 06 '20 at 06:49
  • i get it +1 for that i am also stuck in csrf cookie problem, the easy workaround that i came to know is to comment the csrf_middleware, and i know thats not great solution :D (I am using angular->django, BTW how is react) – Kanishk Tanwar Mar 06 '20 at 06:57
  • 1
    I suppose that's going to be my end solution as well. And react is pretty good. Setting up redux was a pain though. – Sahil Mar 06 '20 at 07:15

2 Answers2

0

I was getting this error because of the fact that my app_name and the url that's used to access the app itself are the same. So my app_name is nordalmail and my url to access the app is also nordalmail.

Now here's the real problem, I have set the root of my website to be the actual admin panel provided by Django itself. So when I made a request to /nordalmail it actually rendered the model lists in the app. All I had to do was change the URL and it worked.

Sahil
  • 1,387
  • 14
  • 41
0

I started a project that requires to accept POST from an external application to django, somehow I wrote the following line in the project urls path('', admin.site.urls, name='admin') I didn't realize right away but this path caused @csrf_exempt to be ignored in my function-based views.

Sahil
  • 1,387
  • 14
  • 41
Zukia
  • 1
  • 1