Django no 'Access-Control-Allow-Origin' header Error

Recently I launched a web app using pythonanywhere and django, and I am trying to validate sign-ins using okta. However, every time I try to log in I get the following error:

Access to fetch at 'https://dev-84844226.okta.com/api/v1/authn' from origin 'https://matthewwong.pythonanywhere.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
POST https://dev-84844226.okta.com/api/v1/authn net::ERR_FAILED

I’m not sure what to do from here, as I believe I have the necessary package installed (django-cors-headers), and I’ve also set CORS_ALLOW_ALL_ORIGINS to True (I’ve also just tried adding the specific URL to CORS_ALLOWED_ORIGINS).

Another thing to note is that this web app works perfectly fine when I host and access it locally off of my own machine (localhost), even without having django-cors-headers imported.

I’m attaching my settings.py code along with the login webpage code where the errors are occurring.

settings.py:

"""
Django settings for mysite project.

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

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

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

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "OMITTED"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['www.msh-rtscheduling.com', 'matthewwong.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "corsheaders",
    "crispy_forms",
    "crispy_bootstrap4",
    "main.apps.MainConfig",
    "register.apps.RegisterConfig",
    'okta_oauth2.apps.OktaOauth2Config',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    'whitenoise.middleware.WhiteNoiseMiddleware',
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

#CORS_ALLOWED_ORIGINS = [
    #'https://matthewwong.pythonanywhere.com',
#]

CORS_ALLOW_ALL_ORIGINS = True

OKTA_AUTH = {
    "ORG_URL": "https://dev-84844226.okta.com",
    "ISSUER": "https://dev-84844226.okta.com/oauth2/default",
    "CLIENT_ID": "OMITTED",
    "CLIENT_SECRET": "OMITTED",
    "SCOPES": "openid profile email offline_access", # this is the default and can be omitted
    "REDIRECT_URI": "https://matthewwong.pythonanywhere.com/accounts/oauth2/callback/",
    "LOGIN_REDIRECT_URL": "/", # default
    "CACHE_PREFIX": "okta", # default
    "CACHE_ALIAS": "default", # default
    "PUBLIC_NAMED_URLS": (), # default
    "PUBLIC_URLS": (), # default
    "STAFF_GROUP": None,
    "SUPERUSER_GROUP": None,
    "MANAGE_GROUPS": False,
    "USE_USERNAME": True, # default
}

ROOT_URLCONF = "mysite.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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 = "mysite.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/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",
    },
]

#Password reset

#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_HOST = 'smtp.gmail.com'
#EMAIL_PORT = 587
#EMAIL_USE_TLS = True
#EMAIL_HOST_USER = ''
#EMAIL_HOST_PASSWORD = ''


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


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

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / 'static'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

CRISPY_TEMPLATE_PACK="bootstrap4"

AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend","okta_oauth2.backend.OktaBackend",)

LOGIN_REDIRECT_URL = "/"
LOGIN_URL = "/accounts/login"
LOGOUT_REDIRECT_URL = "/accounts/login"


# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

login.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
      src="https://global.oktacdn.com/okta-signin-widget/5.11.0/js/okta-sign-in.min.js"
      type="text/javascript"
    ></script>
    <link
      href="https://global.oktacdn.com/okta-signin-widget/5.11.0/css/okta-sign-in.min.css"
      type="text/css"
      rel="stylesheet"
    />
  </head>
  <body>
    <div id="okta-login-container"></div>

    <script type="text/javascript">
      var oktaSignIn = new OktaSignIn({
          baseUrl: '{{config.url}}',
          clientId: '{{config.clientId}}',
          redirectUri: '{{config.redirectUri}}',
          authParams: {
              issuer: '{{config.issuer}}',
              responseType: ['code'],
              scopes: "{{config.scope}}".split(" "),
              pkce: false,
          },
      });
      oktaSignIn.renderEl(
          {el: '#okta-login-container'},
          function (res) {
              console.log(res);
          });
    </script>
  </body>
</html>

Any help would be really appreciated!

I figured it out. I only had CORS allowed on http://localhost:8000 in the Okta developer dashboard. Once I specified the Origin URL of my web app everything worked as intended.

For anyone experiencing the same issue, this should help:
https://developer.okta.com/docs/guides/enable-cors/main/

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.