CORS activando Cross-Origin para Rest Framework en Django

Accediendo desde Angular 5 App a api externa con backend Django.

Poco y nada se puede hacer desde Angular front-end app. 

Primera opcion es configurar  NGINX para que el servidor de la API reciba conexiones externas.

 

location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';

        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
     }
}

 

Con esta confugracion estamos desabilitando toda seguridad desde nuestro backend.

Segundo:

Django-cors-headers:

pip install django-cors-headers

Agregamos a settings:

 

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

 

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

 

CORS_ALLOW_CREDENTIALS = True
CORS_URLS_REGEX = r'^/rest.*$'

CORS_ORIGIN_REGEX_WHITELIST = (r'^(https?://)?(\w+\.)?domain\.com$', )
CORS_ORIGIN_WHITELIST = (
    'localhost:4444',
    '127.0.0.1:4444',
    'domain.com'
    'https://domain.com'
)
CORS_ORIGIN_ALLOW_ALL = True

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

 

De esta forma en nuestro frontend app realizamos el http request:

 let res = this.http.get('https://domain.com/rest/api/');

 

Esta configuracion no permite Autenticacion, por lo tanto:

 let res = this.http.get('https://domain.com/rest/api/', {
      headers: new HttpHeaders().set('Authorization', 'Token XXXxxXxXXxXX'),
      });

 

No da error:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

blog comments powered by Disqus