【问题标题】:Authorization header field absent in request.headers() and request.META when using Apache, Preflight CORS error in browser when using custom header使用 Apache 时 request.headers() 和 request.META 中缺少授权头字段,使用自定义头时浏览器中的 Preflight CORS 错误
【发布时间】:2021-03-04 05:19:02
【问题描述】:

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

  1. 将授权作为标头传递 - 在从 Postman 和 React 进行发布请求时,request.headers("Authorization")request.META["HTTP_AUTHORIZATION"] 未收到标头。

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

  • Postman 工作正常
  • 在 React 上,浏览器抛出错误 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.

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

  1. 将授权作为标头传递,但将运行服务器暴露在 0.0.0.0:8000 而不是 apache https url-
  • 在 Postman 工作
  • 也适用于 React

这是我在sites-enabledsites-available 中的000-default.conf

<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>

【问题讨论】:

  • 这个问题可以使用更多的结构和一些修剪(例如,令牌的值不相关)。现在很难跟上。您是否想说当您直接在 8000 上公开应用程序时,反应正常,但是当您通过 apache 时,您没有获得授权标头?
  • Apparently 您需要将 Apache 配置为不剥离 Authorization 标头。
  • 感谢您纠正@AndrewBacker。我现在修剪了这个问题。是的,暴露在 8000 上使它可以从反应中工作,但是从 apache 上它不能从反应中工作。 (邮递员也没有)。 Apache 以某种方式剥离了 Authorization 标头。
  • @AndrewBacker 这就是为什么我转向自定义标头并尝试在 apache 中工作的 Authorization2..但仅限邮递员。从反应它仍然没有并在浏览器控制台中抛出 cors preflight request 错误..
  • @KevinChristopherHenry 我同意.. 如果我以某种方式阻止 apache 剥离 Authorization 标头,它已排序.. 我分享了我的 000-default.conf 文件你能建议任何更改吗?

标签: reactjs django amazon-ec2 django-rest-framework apache2


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2017-03-07
  • 2021-06-23
  • 2017-03-21
  • 2016-07-15
  • 2018-12-31
  • 2012-11-03
  • 2015-05-11
  • 2017-11-23
  • 1970-01-01
相关资源
最近更新 更多