簡體   English   中英

使用 Apache 時 request.headers() 和 request.META 中缺少授權頭字段,使用自定義頭時瀏覽器中的 Preflight CORS 錯誤

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

我在 AWS EC2 實例上啟動並運行了我的 Rest Framework API。 我已經設置了 Apache 並添加了 SSL 證書。 我正在使用我自己的自定義令牌身份驗證。

  1. 將授權作為標頭傳遞- 在從Postman 和 React執行發布請求時,在request.headers("Authorization")request.META["HTTP_AUTHORIZATION"]未收到標頭。

  2. 傳遞 Authorization2 或 x-api-key 作為標頭-

  • 郵遞員工作正常
  • 在 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處公開 runserver而不是 apache https url-
  • 在郵遞員工作
  • 也適用於 React

這是我在sites-enabled sites-available sites-enabled 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>

因此,我將WSGIPassAuthorization On添加到我的apache.conf文件中,該文件位於sites-enabled之外的父目錄中。 進行這些更改使它像魅力一樣工作,並且 apache 不再剝離Authorization標頭。

以防萬一這可以在將來對其他人有所幫助! 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM