Authorization header missing in PHP POST request
Somehow, the Authorization
header was stripped away. 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]
The most elegant solution to this problem is enabling this directive in .htaccess
.
CGIPassAuth On
This directive is part of the apache core and doesn't require any special module to be enabled. See the documentation here.
The problem happens when using php-fpm with apache (as oposed to using the php module directly in apache).
This is a security measure that prevents sensitive data to be transfered from apache to php through fcgi.
This solution fixes not only $_SERVER["HTTP_AUTHORIZATION"]
but also $_SERVER["PHP_AUTH_USER"]
, used in "Basic" authentication as described
in php's official documentation.
In my opinion, all other solutions that involve setting the HTTP_AUTHORIZATION
environment variable through SetEnvIf
or with RewriteRule
s are workarounds and don't solve the root problem.
I tested this solution in 2021 with php7.4.
I had first to add this to my machines Apache config file:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
On Linux in /etc/apache2/apache2.conf
On Mac using Homebrew in /usr/local/etc/httpd/httpd.conf
On Mac with "native" Apache: /private/etc/apache2/httpd.conf
or: /etc/apache2/httpd.conf
Adding this to .htaccess didn't work for any reason:
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]