pythondjangodjango-rest-frameworkcorsdjango-cors-headers

Custom header "X-API-Version" throws CORS error Django REST framework


I tried to add a custom header called "X-API-Version" to check if the front-end is up to date, but despite following the documentation instructions I got a CORS error.

Access to XMLHttpRequest at 'http://192.168.5.39:8001/api/host/login/'
from origin 'http://localhost:9000' has been blocked by CORS policy:
Request header field x-api-version is not allowed by Access-Control-Allow-Headers
in preflight response.

I already installed the django-cors-headers package, added it to INSTALLED_APPS, added 'corsheaders.middleware.CorsMiddleware' and 'django.middleware.common.CommonMiddleware' in MIDDLEWARE and I also added x-api-version to CORS_ALLOW_HEADERS and CORS_ORIGIN_ALLOW_ALL = True but the error still persists.

What could I do to prevent this error from happening? Is there another way to add a custom header? Thanks for helping

Here is the settings file:

from corsheaders.defaults import default_headers
from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
import django.core.mail.backends.smtp

BASE_DIR = Path(_file_).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', False)

EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend



SERVER_EMAIL = EMAIL_HOST_USER

# VARIAVEIS DE AMBIENTE API VIASAT

IXC_TOKEN = os.environ.get(
    'TOKEN',
    '*'
)

IXC_API = os.environ.get(
    'API',
    'https://nameturbo.com.br/webservice/v1'
)

IXC_PRODUTO = os.environ.get('PRODUTO', '27,73')

IXC_UF = os.environ.get('UF', '10')

IXC_CRT_DINHEIRO = os.environ.get('DINHEIRO', '6')

IXC_CRT_PIX = os.environ.get('PIX', '8')

VENCIMENTO_HOST = os.environ.get('VENCIMENTO_HOST', '25')

ID_PLANO_INVALIDO = os.environ.get('ID_PLANO_INVALIDO', ['15', ])

ALLOWED_HOSTS = ['*', ]

CSRF_TRUSTED_ORIGINS = [
    'https://*',
    'http://*',
    'https://*',
    'http://*',
]

CORS_ALLOWED_HEADERS = list(default_headers) + ['HTTP_X_API_VERSION', 'X-API-VERSION', 'x-api-version']


CORS_ALLOW_ALL_ORIGINS = True

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',
    'rest_framework.authtoken',
    'rest_framework',
    'django_celery_results',
    'django_celery_beat',
    'corsheaders',
    'drf_yasg',
    'api'
]

MIDDLEWARE = [
    'api.middleware.VersionAPIMiddleware',
    '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',
    'corsheaders.middleware.CorsMiddleware',

]

ROOT_URLCONF = 'name_api.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 = 'name_api.wsgi.application'


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


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

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

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

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


SWAGGER_SETTINGS = {
    'LOGIN_URL': '/admin/login/',
    'LOGOUT_URL': '/admin/logout/',
    'DOC_EXPANSION': 'none',
    'DEFAULT_MODEL_RENDERING': 'exemple'
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 50
}

# Versão API
VERSION = os.environ.get('VERSION', 2)

And here is the middleware file:

from nome_api.settings import VERSION
from django.http import JsonResponse

class VersionAPIMiddleware:
    def _init_(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def _call_(self, request):
        ver_request = int(request.META.get('HTTP_X_API_VERSION', 0))

        # Load page swagger and page django-admin
        if len(request.path) == 1 or '/admin/' in request.path:
            response = self.get_response(request)
            return response

        # Verify version API
        if ver_request == VERSION:
            response = self.get_response(request)
            return response
        else:
            # Resquest page swagger
            if 'HTTP_X_CSRFTOKEN' in request.META:
                response = self.get_response(request)
                return response
            else:
                return JsonResponse({'msg': 'favor atualizar o aplicativo'}, status=401)


Solution

  • In settings.py replace CORS_ALLOWED_HEADERS with CORS_ALLOW_HEADERS and it should work.