Postman request to django with csrf works but not with request in NextJS

I’m currently working on a login system that needs a POST request and csrf authentication, so I started to work with postman and trying to send requests and took the snippet provided by the generator:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const myHeaders = new Headers();
myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h");
myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h");
const requestOptions = {
method: "POST",
headers: myHeaders,
redirect: "follow"
};
fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error));
</code>
<code>const myHeaders = new Headers(); myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); const requestOptions = { method: "POST", headers: myHeaders, redirect: "follow" }; fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions) .then((response) => response.text()) .then((result) => console.log(result)) .catch((error) => console.error(error)); </code>
const myHeaders = new Headers();
myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h");
myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h");

const requestOptions = {
  method: "POST",
  headers: myHeaders,
  redirect: "follow"
};

fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

The request above works in postman but if I took this code and write it in nextjs a got the forbidden error
[30/Apr/2024 13:11:47] "POST /simulazione/api/prova_token/ HTTP/1.1" 403 2869

These below are the django view and settings:
View

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@csrf_protect
def prova_token(request):
if request.method == 'POST':
return JsonResponse("hello", safe=False)
</code>
<code>@csrf_protect def prova_token(request): if request.method == 'POST': return JsonResponse("hello", safe=False) </code>
@csrf_protect
def prova_token(request):
    
    if request.method == 'POST':
    
        return JsonResponse("hello", safe=False)

Settings

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
#CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_SAMESITE = None
ALLOWED_HOSTS = [ ]
CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'csrftoken',
'x-requested-with',
]
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
CORS_ALLOWED_ORIGINS = [
'http://127.0.0.1:3000',
'http://localhost:3000',
]
# Application definition
INSTALLED_APPS = [
'corsheaders',
'simulazione.apps.SimulazioneConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_nextjs',
'rest_framework',
]
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',
]
</code>
<code>CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True #CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = None ALLOWED_HOSTS = [ ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'simulazione.apps.SimulazioneConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nextjs', 'rest_framework', ] 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', ] </code>
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

#CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_SAMESITE = None

ALLOWED_HOSTS = [ ]
CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"]

CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'csrftoken',
'x-requested-with',
]

CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:3000',
    'http://localhost:3000',
]
# Application definition

INSTALLED_APPS = [
    'corsheaders',
    'simulazione.apps.SimulazioneConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_nextjs',    
    'rest_framework',
]

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',
]

I tried to make the request sending the csfr as header and I expected to access the method of the view

New contributor

Andrea Di Donato is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật