首页 > 解决方案 > 使用 Apache 时 request.headers() 和 request.META 中缺少授权头字段,使用自定义头时浏览器中的 Preflight CORS 错误

问题描述

我在 AWS EC2 实例上启动并运行了我的 Rest Framework API。我已经设置了 Apache 并添加了 SSL 证书。我正在使用我自己的自定义令牌身份验证。

  1. 将授权作为标头传递- 在来自Postman 和 React的发布请求时,标头未在request.headers("Authorization")and中接收request.META["HTTP_AUTHORIZATION"]

  2. 将 Authorization2 或 x-api-key 作为标头传递-

我已经尝试在 React 中包含 Access-control-origin Header 并在后端设置 django-cors-headers。但这无济于事。

  1. 将授权作为标头传递,但将 runserver 暴露在0.0.0.0:8000而不是 apache https url-

这是我000-default.conf的两个sites-enabledsites-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>

标签: reactjsdjangoamazon-ec2django-rest-frameworkapache2

解决方案


所以我添加WSGIPassAuthorization On到我的apache.conf文件中,该文件位于sites-enabled. 进行这些更改使其像魅力一样工作,并且 apache 不再剥离Authorization标题。

以防万一这对将来的其他人有帮助!谢谢!


推荐阅读