Blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'
f4ww4z opened this issue · comments
Understanding CORS
- I have read the resources.
Python Version
3.8.10
Django Version
3.2.9
Package Version
3.10.0
Description
When requesting any of my django server's resource from a different domain, I got this error:
Access to XMLHttpRequest at 'http://0.0.0.0:8000/api/v1/company' from origin 'http://127.0.0.1:8003' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I read the docs and I made sure not to allow all origins. Here's my settings.py
:
# ...
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
# ...
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
CORS_ALLOWED_ORIGINS = [
os.environ["FRONTEND_URL"]
]
CSRF_TRUSTED_ORIGINS = [
os.environ["FRONTEND_URL"]
]
SESSION_COOKIE_SAMESITE = None
CORS_ALLOW_CREDENTIALS = True
where FRONTEND_URL
is http://127.0.0.1:8003
, my frontend url.
upon checking the request, I found that 'Access-Control-Allow-Origin' is indeed set to '*' :
Why and how was this set? I made sure that CORS_ALLOW_ALL_ORIGINS
set to false.
How can I solve this error? Thanks
Actually I found the root cause: I ran the Django server at host 0.0.0.0
, which somehow sets allow all origin to *
. Changing it to localhost
fixes the issue.
Actually I found the root cause: I ran the Django server at host
0.0.0.0
, which somehow sets allow all origin to*
. Changing it tolocalhost
fixes the issue.
localhost
is treated differently to the browser. Django doesn't change anything. Read the resources for more info.