django4.2 post forbidden

created a new project using Django 4.2.7. When I tested an API endpoint, I received a 200 response for a GET request, but a 403 Forbidden response for a POST request. I am using Python 3.10.11 with Django 4.2.7 and django-cors-headers 4.3.0. I followed the instructions on the django-cors-headers official website to configure CORS in my settings.py file and restarted the server, but I am still experiencing CORS issues. I am not a beginner developer. The specific error message is: Forbidden (CSRF cookie not set.)

INSTALLED_APPS add 'corsheaders'    
MIDDLEWARE add 'corsheaders.middleware.CorsMiddleware'
CORS_ALLOWED_ORIGINS = []
CORS_ALLOWED_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
]
CORS_ALLOWED_HEADERS = [
    'Accept',
    'Content-Type',
]
CORS_ALLOW_CREDENTIALS = True

urls.py

from django.contrib import admin
from django.urls import path
from qm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
]

views.py

from django.http import HttpResponse


# Create your views here.


def index(request):
    if request.method == 'GET':
        return HttpResponse("123")
    if request.method == 'POST':
        return HttpResponse("456")
    else:
        return HttpResponse("789")
1 Like

The error is not because of CORS, it is because of CSRF. In your settings add the url like this

CSRF_TRUSTED_ORIGINS=['http://127.0.0.1:8000',]

I add CSRF_TRUSTED_ORIGINS = [‘http://127.0.0.1:8000’, ] but 403 Forbidden (CSRF cookie not set.): /

Is there any specific page where you are getting this error.
Also are you running your django project same as http://127.0.0.1:8000 this url.

this one startapp but i add CSRF_TRUSTED_ORIGINS = [‘http://127.0.0.1:8000’, ]
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False in settings.py but error 403 Forbidden (CSRF cookie not set.): /

urls.py
from django.contrib import admin
from django.urls import path
from qm import views

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘’, views.index, name=‘index’),
]
views.py
from django.http import HttpResponse

Create your views here.

def index(request):
if request.method == ‘GET’:
return HttpResponse(“123”)
if request.method == ‘POST’:
return HttpResponse(“456”)
else:
return HttpResponse(“789”)

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
“corsheaders”,
‘qm’,
]

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘corsheaders.middleware.CorsMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]

no i get a forbidden

I put # ‘django.middleware.csrf.CsrfViewMiddleware’, The issue has been resolved.

Side note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I have taken the liberty of correcting the original post, it may be helpful if you made the same changes to your other posts in this thread.)

The issue has not been resolved. You have now exposed your site to cross-site forgery request attacks, putting your users - and possibly your site - at risk.

How are you issuing the requests for the page throwing this error? Are you making requests using the browser or are you accessing your site with a JavaScript front end?

Thanks KenWhitesell. I using postman post my django project api.
Finally, I using django rest framework.

Are you posting the csrf cookie along with the csrf token in your POST?

Also see the docs at How to use Django’s CSRF protection | Django documentation | Django.

I know from

 #my views.py
from django.views.decorators.csrf import csrf_exempt

@csrf_exampt 
def index(self, request):
     ...

help me. but I using django rest framework ‘rest_framework.authentication.TokenAuthentication’.

The issue might not be in your code. It might be in how you’re trying to issue the POST.

Are you posting the csrf cookie along with the csrf token in your POST?

Please show exactly what you are submitting as the request.

Note: The TokenAuthentication is something in addition to, and completely indepdentent of the CSRF-related elements.

my code

# urls.py
from django.contrib import admin
from django.urls import path, include
from qm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),

]
# qm/views.py
from django.http.response import JsonResponse


def index(request):
    return JsonResponse({"message": "ok"})

I use the code request below

import requests
res = requests.get("http://localhost:8000")
print(res.status_code)
# 403

Try putting the trailing ‘/’ on the end of that URL ("http://localhost:8000/")

image.png

Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> 于2023年11月8日周三 11:56写道:

settings.py

"""
Django settings for xx project.

Generated by 'django-admin startproject' using Django 4.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+euvk!tcqw@yb0zthe5qhi8c48pl%a2vb=@)4l=r!(imlpda#%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'x1',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'xx.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'xx.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

urls.py

"""
URL configuration for xx project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from x1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
]

x1/views.py

from django.http.response import JsonResponse


def index(request):
    return JsonResponse({"message": "ok"})