Authorization header missing in PHP POST request

蹲街弑〆低调 提交于 2019-11-27 11:05:56

问题


I'm currently trying to read the authorization header in a PHP script that I'm calling with a POST request. The Authorization header is populated with a token. It seems the Authorization header is somehow removed before it arrives at my PHP script. I'm executing the post request with Postman (Chrome addon) and I enabled CORS in my PHP script. I don't have access to the apache server directly.

HTTP Request:

Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,ja;q=0.2
Authorization:Bearer mytoken
Cache-Control:no-cache
Connection:keep-alive
Content-Length:32
Content-Type:text/plain;charset=UTF-8
Host:www.myhost.com
Origin:chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)       
 Chrome/38.0.2125.104 Safari/537.36

PHP script:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type,      Accept");
header("Content-Type: application/json");

$headers = getallheaders();
echo $headers['Authorization'];

The above script outputs '' (= nothing).


回答1:


After quite some time a found a solution to this problem. Somehow the Authorization header was stripped away and by adding the following lines in my .htaccess I was able to get it to work.

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]



回答2:


I had first to add this to my machines Apache config file:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

For Linux in /etc/apache2/apache2.conf

For Mac (using Homebrew) in /usr/local/etc/httpd/httpd.conf

Adding this to .htaccess didn't work for any reason:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]



回答3:


Below array holds request headers, that may be missing in $_SERVER variable

$headers = apache_request_headers();

(Especially true for 'HTTP_X_REQUESTED_WITH' ajax header, which will be found this way as: $headers['X_REQUESTED_WITH']




回答4:


I don't know why my php 5.4.45 running on NGINX was refusing any custom header containing underscores:

ACCEPTED: CURLOPT_HTTPHEADER => array('Authorization: 123456')

REFUSED: CURLOPT_HTTPHEADER => array('my_Authorization: 123456')

I hope it can help someone. Cheers



来源:https://stackoverflow.com/questions/26475885/authorization-header-missing-in-php-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!