djangoreactjscsrf-token

csrf_exempt Decorator does not work in Django function based views


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.


Solution

  • 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.