Authorization header field absent in request.headers() and request.META when using Apache, Preflight CORS error in browser when using custom header

Viewed 749

I have my Rest Framework API's up and running on an AWS EC2 instance. I have set up Apache and added SSL certificate. I'm using my own custom token authentication.

  1. Passing Authorization as header - On doing post request from both Postman and React, the header is not received in request.headers("Authorization") and request.META["HTTP_AUTHORIZATION"].

  2. Passing Authorization2 or x-api-key as header -

  • Works fine from Postman
  • On React, browser throws error Access to fetch at 'https://www.myapi.live/api/project/add/8/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization2 is not allowed by Access-Control-Allow-Headers in preflight response.

I have already tried including Access-control-origin Header in React and setting django-cors-headers at backend. But it doesn't help.

  1. Passing Authorization as header but exposing runserver at 0.0.0.0:8000 instead of apache https url-
  • Works in Postman
  • Works in React too

Here's my 000-default.conf in both sites-enabled and sites-available

<VirtualHost *:80>
ServerName www.myapi.live
ServerAdmin webmaster@localhost
DocumentRoot /home/ubuntu/django/project
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /static /home/ubuntu/django/project/static
<Directory /home/ubuntu/django/project/static>
Require all granted
</Directory>
<Directory /home/ubuntu/django/project/project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess project python-path=/home/ubuntu/django/project python-home=/home/ubuntu/django/myenv
WSGIProcessGroup project
WSGIScriptAlias / /home/ubuntu/django/project/project/wsgi.py
WSGIPassAuthorization On
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.myapi.live
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</VirtualHost>
1 Answers

So I added WSGIPassAuthorization On to my apache.conf file which resides in the parent directory just outside of sites-enabled. Doing these changes made it work like a charm and apache no longer strips the Authorization header.

Just in case this can be of help to someone else in future! Thanks!

Related