【发布时间】:2021-03-04 05:19:02
【问题描述】:
我的 Rest Framework API 已在 AWS EC2 实例上启动并运行。我已经设置了 Apache 并添加了 SSL 证书。 我正在使用我自己的自定义令牌身份验证。
-
将授权作为标头传递 - 在从 Postman 和 React 进行发布请求时,
request.headers("Authorization")和request.META["HTTP_AUTHORIZATION"]未收到标头。 -
将 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。但这无济于事。
-
将授权作为标头传递,但将运行服务器暴露在
0.0.0.0:8000而不是 apache https url-
- 在 Postman 工作
- 也适用于 React
这是我在sites-enabled 和sites-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