No 'Access-Control-Allow-Origin' header on the requested resource in Django - django

I have read relevant question and understand what is cors.
I followed each step.
Install
pip install django-cors-headers
Add
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'a9.core.access.middleware.AccessMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
INSTALLED_APPS = ['corsheaders','otree']
And
python3 manage.py migrate
However, I still get the error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1
Is there something I am missing to make it work correctly?

Using 127.0.0.1 NOT localhost did the trik.

Related

Django, CORS "Access-Control-Allow-Origin" error

Can't figure out what's wrong with my Django DRF api endpoint. I'm getting a CORS error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS
header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
Problem is, I followed every step online to fix this.
I've installed 'django-cors-headers'
Added corsheaders app to INSTALLED_APPS above rest_framework
and the app that includes api endpoint.
Added cors middleware to the top of the middleware list in
settings.py
Added 'CORS_ALLOWED_ORIGINS = ('http://localhost:3000' # React
app) (Also tried with CORS_ORIGIN_ALLOW = True)
Quadruple-checked that API POST request includes a trailing slash.
Nothing seems to fix it. Am I forgetting something? Thanks for any help.
This is my settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'core.apps.CoreConfig',
]
CORS_ALLOWED_ORIGINS = (
'http://localhost:3000', # for localhost (REACT Default)
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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',
'django.middleware.common.CommonMiddleware',
]
Not sure how revelant it is, but If I send POST request from insomnia, it works fine, but from React, it doesn't, this is my react request just in case:
const postSomeData = async () => {
const res = await axios.post(
"http://127.0.0.1:8000/api/",
{ promptQuery: "pls just work already" },
{
headers: {
"Content-Type": "application/json",
},
}
);
};
Thank you!
The code looks fine ,it seems middleware order issue. Would you try putting corsheader middle between sessionmiddleware and commonmiddleware ..
something like this :
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', #here
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
since the order of middleware matters.

Django middleware when using msal for authentication

I Have implemented oauth2 login for users in a django app using the msal library following this guide https://medium.com/#madhok.simran8/how-to-setup-azure-oauth-2-0-sso-in-django-with-microsoft-graph-api-d2639b8f7e36.
However Im not able to set the request.user variable right, which in turn means i cant check if request.user.is_authenticated.
I believe this should be solved using the proper middleware, but Im not sure how to set it up.
This is my current middleware:
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',
]

What's the proper order in which Django cache middleware should be added?

I'm trying to add caching to my Django project and I'm failing to understand documentation on middleware ordering. Consider the following MIDDLEWARE list, which is mostly default:
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',
'simple_history.middleware.HistoryRequestMiddleware'
]
If I'm understanding this piece of documentation correctly, I'm supposed to add three new entries to MIDDLEWARE list. Is there more than one proper ordering for my case?
The default startproject middleware are:
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',
]
The three per-site cache middleware are given as:
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
And when we're discussing caching there's also ConditionalGetMiddleware which is related to conditional view processing:
MIDDLEWARE = [
'django.middleware.http.ConditionalGetMiddleware'
]
The question is then, what is the proper order to combine all these into one single MIDDLEWARE list? The Django documentation gives two rules specific to caching:
UpdateCacheMiddleware must come before "any other middleware that might add something to the Vary header" (and SessionMiddleware, GZipMiddleware, LocaleMiddleware do)
FetchFromCacheMiddleware needs to run after middleware that varies Vary
While it could be more subtle if you have additional custom stuff, the most natural way based on the defaults is to just bracket all the other middleware inside the cache ones. But we'll leave SecurityMiddleware up top since afaict it just checks/redirects some stuff that would be better done by something [e.g. nginx] wrapping Django itself anyway.
The CommonMiddleware was included at presumedly the right place in the startproject list already, so that one's easy.
The ConditionalGetMiddleware is tricker; a separate section of Middleware ordering hints say it goes "after GZipMiddleware […]" but overall "before any middleware that may change the response" which is a bit odd but whatever…. (Apparently the GZip middleware is discouraged/problematic anyway.)
At the end here's what I get:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.gzip.GZipMiddleware', # Caution: BREACH attack?
'django.middleware.http.ConditionalGetMiddleware',
'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',
'django.middleware.cache.FetchFromCacheMiddleware',
]
Note that there's at least one odd interaction between ConditionalGetMiddleware and UpdateCacheMiddleware in that the former may prevent the latter from actually caching the render if/when that render gets replaced with a 304 response.
So perhaps even better would be:
MIDDLEWARE = [
'django.middleware.http.ConditionalGetMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'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',
'django.middleware.cache.FetchFromCacheMiddleware',
]
…avoiding Gzip and handling HTTPS/HSTS stuff in the HTTP server layer instead.

No 'Access-Control-Allow-Origin' header is present on the requested resource error in fetch API django

I'm trying to fetch some data from an API. It works and my data is sent to the server but I am getting the following error message that not allow me to continue:
Access to fetch at 'http://192.168.80.11:8000/upload/5bc4206e3ff2286d24c58899/' from origin 'http://localhost:8000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I know that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS.
But how can I set Access-Control-Allow-Origin in the response header?
I use Django.
And this is setting file on server:
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGINE_ALLOW_ALL= True
CORS_ALLOW_CREDENTIALS = True
#CORS_ORIGINE_ALLOW_ALL= False
CORS_ORIGINE_WHITELIST=(
'http//:192.168.20.29:8000',
'http//:192.168.20.30:8000',
'http//:127.0.0.1:8000',
)
Did you add this to your installed apps?
INSTALLED_APPS = (
...
'corsheaders',
...
)
UPDATE
CORS_ORIGIN_ALLOW_ALL not CORS_ORIGINE_ALLOW_ALL
CORS_ORIGIN_WHITELIST not CORS_ORIGINE_WHITELIST

#csrf_protect in django services

I'm trying to use #csrf_protect in my services by following Cross Site Request Forgery protection article but it is not working for me.
This is my settings file
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
and this is how I'm Acquiring the token
var csrftoken = Cookies.get('csrftoken');
And this is how I'm configuring the $http provider with the cookie and header names:
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
But when I call any service, it returns 403 forbidden error. Any Idea what I'm missing or doing wrong?
Any kind of help will be appreciated.