1

cors-header using pip on Django 2.0.6 . Still same origin error is occuring. I installed a chrome extension Allow-Controll-Allow-Origin:* when I enable all things are fine.

My setting files are

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

]


CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

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

still in browser I am getting

Failed to load https://s3.amazonaws.com/django/Events/Test1/1.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8002' is therefore not allowed access.

And this

19:367 Uncaught Error: InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').
    at XMLHttpRequest.xhr.onreadystatechange (19:328)








**Full settings.py**


"""
Django settings for demo project.

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

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

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

import os
from os.path import dirname, abspath, join, normpath

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<key>'
import ssl
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

CORS_ORIGIN_ALLOW_ALL = True
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cruds_adminlte',
    'testapp',
    'django_ajax',
    # 'storages',
    'django_dropbox',
    'django_select2',
    'corsheaders'


]

AWS_S3_ACCESS_KEY_ID = '<access key>'     # enter your access key id
AWS_S3_SECRET_ACCESS_KEY = '<key>' # enter your secret access key
AWS_STORAGE_BUCKET_NAME = 'ais-django'
AWS_ACCESS_KEY_ID = '<id>'
AWS_SECRET_ACCESS_KEY = '<access key>'





# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
# AWS_S3_SECURE_URLS = False       # use http instead of https
# AWS_QUERYSTRING_AUTH = False     # don't add complex authentication-related query parameters for requests
# AWS_S3_ACCESS_KEY_ID = '<access key>'     # enter your access key id
# AWS_S3_SECRET_ACCESS_KEY = '<key>' # enter your secret access key
# AWS_STORAGE_BUCKET_NAME = 'ais-django'
# AWS_ACCESS_KEY_ID = '<key>'
# AWS_SECRET_ACCESS_KEY = '<key>'
# AWS_SECRET_ACCESS_KEY = ''
# AWS_STORAGE_BUCKET_NAME = ''
# AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
# AWS_S3_OBJECT_PARAMETERS = {
#     'CacheControl': 'max-age=86400',
# }
# AWS_LOCATION = '/static/'
#
# STATICFILES_DIRS = [
#      os.path.join(BASE_DIR, 'testapp/static/img'),
#  ]
# STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
# # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'



# if hasattr(ssl, '_create_unverified_context'):
#    ssl._create_default_https_context = ssl._create_unverified_context





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

]


CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

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


ROOT_URLCONF = 'demo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            normpath(join(dirname(dirname(abspath(__file__))),
                          'demo', 'templates')),
        ],
        '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 = 'demo.wsgi.application'


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

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        # 'ENGINE': 'django.db.backends.postgresql_psycopg2',
        # 'NAME':'aisdb',
        # 'USER' : 'root',
        # 'PASSWORD':'admin123',
        # 'HOST':'localhost',
        # 'PORT':'',
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
# django-crispy-forms
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# django-crispy-forms

INTERNAL_IPS = ('127.0.0.1',)

from easy_thumbnails.conf import Settings as thumbnail_settings
THUMBNAIL_PROCESSORS = (
    'image_cropping.thumbnail_processors.crop_corners',
) + thumbnail_settings.THUMBNAIL_PROCESSORS
IMAGE_CROPPING_JQUERY_URL = None

LOGIN_REDIRECT_URL = '/login'

TIME_FORMAT = 'h:i A'
DATETIME_FORMAT = 'm/d/Y H:i:s'
DATE_FORMAT = "m/d/Y"

TIME_INPUT_FORMATS = ['%I:%M %p']


STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')



MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

if not os.path.exists(MEDIA_ROOT):
    os.makedirs(MEDIA_ROOT)
Zoe
  • 27,060
  • 21
  • 118
  • 148
gamer
  • 603
  • 4
  • 20
  • You've accidentally posted various private keys. I've removed them and flagged for revision redaction, but it's too late (scrapers have gotten access to it, this is just to make it harder to find). In the unlikely event you're still using those keys, I highly advice you change them now, before they're abused. – Zoe Aug 14 '19 at 14:53
  • It appears that you have posted sensitive/private information. Please reset your passwords and/or revoke API keys and tokens, as they are considered compromised when posted on the internet. If personally-identifiable information was posted, please [edit] out the info then flag your post for a moderator to redact the prior revisions. – Samuel Liew Aug 15 '19 at 01:16

3 Answers3

0

What is about ALLOWED_HOSTS = ['*'] ? This should solve your problem.

Another reason could be that, you also have to set the CORS in your Amazon storage.

One of these two things should work for you.

SSKhn
  • 15
  • 7
Coder949
  • 987
  • 1
  • 8
  • 29
0

Try adding corsheaders to INSTALLED_APPS = ( ....., 'corsheaders' )

MIDDLEWARE_CLASSES = [ ... 'corsheaders.middleware.CorsMiddleware', ... 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', ... ]

arunp9294
  • 767
  • 5
  • 15
0

Have a look at this

https://stackoverflow.com/a/29774990/9216722

I think your request is going from client side. Need Access-Control-Allow-Origin "*" settings in client request if thats the case

Mask your credentials in settings file you shared

arunp9294
  • 767
  • 5
  • 15