Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4105

Getting CSRF 403 error with django server and nexjs client

$
0
0

I am sending requests to Django server from next.js but I am getting error :403 Forbidden (CSRF cookie not set.), even after sending the csrf token.

I am running both Django server and next.js locally.

Requesting to same api from postman/insomnia works perfectly fine but not with my next.js app.

I did some digging and found it may be issue with CORS, so I did some changes in settings.py but still getting same error.

Please help me understand what is going wrong, how I can debug, and what changes should I make.

First, I fetch CSRF token using another API which works fine.Then in second api, I add my CSRF token.

fetching in Next.js

      const uploadFile = async () => {        // Select file from input element or any other method        const fileInput = document.getElementById('fileInput');        const file = fileInput.files[0];        const form = new FormData();        form.append("image", file);        const options = {          method: 'POST',          headers: {            cookie: 'csrftoken=2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI','Content-Type': 'multipart/form-data; boundary=---011000010111000001101001','X-CSRFToken': '2V7dKpZXLN24pLDdDkub9GxM2ljzI0nI'          }        };        options.body = form;        fetch('http://127.0.0.1:8000/getinfo', options)          .then(response => response.json())          .then(response => console.log(response))          .catch(err => console.error(err));      };

my settings.py in Django :

# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = ['mymedic.pythonanywhere.com','127.0.0.1',]# Application definitionINSTALLED_APPS = ['backend.apps.BackendConfig','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','corsheaders']MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','corsheaders.middleware.CorsMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.middleware.common.CommonMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]CSRF_COOKIE_HTTPONLY=FalseSESSION_COOKIE_SECURE=FalseCSRF_COOKIE_SECURE=FalseCORS_ALLOW_CREDENTIALS = True# https://stackoverflow.com/questions/53215045/redirect-is-not-allowed-for-a-preflight-requestCORS_ALLOW_HEADERS = ('accept','accept-encoding','authorization','content-type','dnt','origin','user-agent','x-csrftoken','x-requested-with','user','apikey','Referer','credentials','image,''username',)CORS_ALLOWED_ORIGINS = ['http://localhost:3000',  # Add the origin of your Next.js application]CORS_ALLOW_ALL_ORIGINS = False  # Disable allowing all originsCSRF_TRUSTED_ORIGINS = ['http://localhost:3000','https://*.mydomain.com','https://*.127.0.0.1']

Viewing all articles
Browse latest Browse all 4105


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>