Django CORS allowing requests from non-allowed origin - python

I have Django CORS running with an allowed origin list that looks like this:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
'http://127.0.0.1:8000',
'http://127.0.0.1:3000',
]
Yet if I request this using Python's requests library in my terminal it still allows the request. I've even tried only allowing requests from https://google.com, but it still allows me to use my API.
Why is this? (I'm still new to Django, so sorry if this is a bad question)
Here are some other settings
Installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# internal
'my_app1',
'my_app2',
'my_app3',
# third party
'rest_framework',
'corsheaders',
'debug_toolbar',
]
Middleware:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'django_user_agents.middleware.UserAgentMiddleware',
]

From mozilla CORS docs
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
It is browser mechanism and has nothing to do with API protection in sense you are misinterpreting it

Related

¿Why my CORS config in django is not working?

I have my REST API settings in my production.py file. This REST API is uploaded to Heroku and uses django-cors-headers with the following configuration:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-Party apps
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'gunicorn',
# Local apps
'core',
'users',
'checkers',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'myapi.herokuapp.com'
)
The idea when putting myapi.herokuapp.com in CORS_ORIGIN_WHITELIST is to see if making the request from localhost is rejected (it would be the right thing to do). But this is accepted which gives me to understand that CORS is not working well.
before fetch the django rest_api, make sure you setup django-cors-headers in your backend settings.py. for more information take a look at this link.
pip install django-cors-headers
settings.py :
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'your-server-IP-address'
)
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

django-tenant-schema enable Admin module for all tenants

I am setting up django with multitenant architecture. I went through the https://django-tenant-schemas.readthedocs.io/en/latest/install.html
instruction and get to the point that have inital startup screen.
What I want to achieve is to enable admin module for each tenant.
my in settings.py I have following:
#Application definition
SHARED_APPS = (
'tenant_schemas', # mandatory, should always be before any django app
'customers', # you must list the app where your tenant model resides in
'django.contrib.contenttypes',
# everything below here is optional
)
TENANT_APPS = (
'django.contrib.contenttypes',
# your tenant-specific apps
# 'myapp.hotels',
# 'myapp.houses',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
)
INSTALLED_APPS = [
'tenant_schemas',
'customers',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
]
TENANT_MODEL = "customers.Client"
MIDDLEWARE = [
'tenant_schemas.middleware.TenantMiddleware',
'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 = 'sitemanager.urls'
PUBLIC_SCHEMA_URLCONF = 'sitemanager.urls_public'
when trying to open http://localhost:8000/admin getting error:
DoesNotExist at /admin/login/
Site matching query does not exist.
Request Method: GET
Request URL: http://localhost:8000/admin/login/?next=/admin/
Django Version: 2.1.2
Exception Type: DoesNotExist
Exception Value:
Site matching query does not exist.
my urls.py:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
What am I missing in configuration?
Adding PUBLIC_SCHEMA_NAME = 'public' sort the problem.
I think django.contrib.sites should be in SHARED_APPS.
Kudos for using django-tenant-schema +1
Then to create a superuser :./manage.py tenant_command createsuperuser
Might be handy.

django-cors-headers settings.py django app not working even though I've added all the requirements to settings.py

So, I'm using django-cors-headers with Rest Framework with Django 1.11.x, and I've pretty much followed the general advice, and yet, I'm still getting x has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." As you can see, I've added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to Middleware, and I've set CORS_ORIGIN_ALLOW_ALL to true and CORS_ALLOW_CREDENTIALS to true, too. I've even included a whitelist option, though it's my understanding that, if CORS_ORIGIN_ALLOW_ALL is set to true, the whitelist isn't needed. I've also pip3 install django-cors-headers. What is the deal??? BTW, I've read the README on the django-cors-headers repo. I want to know why it's not working.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'books.apps.BooksConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = (
'localhost:5555'
)
And my js file that's accessing from localhost:5555 is:
var request = $.ajax({
type: 'GET',
url: url,
dataType: 'json',
xhrFields: {
withCredentials: true
}});

'WSGIRequest' object has no attribute 'session' while upgrading from django 1.3 to 1.9

Similar to this question 'WSGIRequest' object has no attribute 'session'
But my MIDDLEWARE classes are in the correct order.
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.staticfiles',
'membership',
'treebeard',
'haystack',
'reversion',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
I am redirecting to login
url(r'^$', RedirectView.as_view(url='login/')),
url(r'^login/$', 'membership.views.loginView', name='login'),
and then
def loginView(request):
a = request.session
Throws the error
MIDDLEWARE is a new setting in 1.10 that will replace the old MIDDLEWARE_CLASSES.
Since you're currently on 1.9, Django doesn't recognize the MIDDLEWARE setting. You should use the MIDDLEWARE_CLASSES setting instead:
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Django 2.0
You can try this in your settings.py, MIDDLEWARE_CLASSES = [....]:
Change MIDDLEWARE_CLASSES=[...] to MIDDLEWARE=[...]
Remove SessionAuthenticationMiddleware from the MIDDLEWARE=[...] list.
The MIDDLEWARE_CLASSES setting is deprecated in Django 1.10, and
removed in Django 2.0.
The SessionAuthenticationMiddleware class is removed. It provided no
functionality since session authentication is unconditionally enabled
in Django 1.10.
This error can also be thrown when you have a typo. i.e.
request.sesion ...
instead of
request.session ...
Check the order of the middleware, if you are trying to access it on some middlewares which are listed above the session middleware, you will get this error.

Retrieve data from API REST Django and Angular

I'm trying to retrieve the json from the rest api set up using Django.
This data is currently only hosted on: http://127.0.0.1:8000/xyz
When I try to retrieve it using
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/xyz',
})
I get an error that is:
XMLHttpRequest cannot load http://127.0.0.1:8000/xyz. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access.
Can someone tell me a way of dealing with this, please?
Thanks!
Here's my Django settings folder:
INSTALLED_APPS = (
'student',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders'
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.common.CommonMiddleware'
)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
'http://127.0.0.1:8000/'
)
Look into using django-cors-headers to have Django return the proper headers. You can then create a whitelist for your site (http://127.0.0.1:8080 for development and whatever your final domain for production)
I use the following on my settings for a similar setup:
INSTALLED_APPS += ('corsheaders',)
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api.*$'
CORS_ORIGIN_WHITELIST = (
'mydomain',
'localhost:3000',
)
You may also need to add the following to your Angular project:
$http.defaults.useXDomain = true;
[UPDATE]
See this blog for more details
Apart from the changes in settings.py, please try to add a slash at the end of the url you are calling
$http({
method: 'GET',
- url: 'http://127.0.0.1:8000/xyz',
+ url: 'http://127.0.0.1:8000/xyz/',
})

Categories

Resources