HTTP_AUTHORIZATION

做接口认证的时候,我们常会采用Http BearerAuth认证方式,即请求时在Header带上Authorization参数:

Authorization: Bearer your_token

我们都知道php的自定义头信息都可以使用$SERVER['HTTP*']来获取, 如 “Cookie: BAIDUID=B86A8A0FF:”, 获取的时候,我们可以使用$_SERVER['HTTP_COOKIE']来获取。

Authorization是个例外,在Apache服务器下会出现$_SERVER['HTTP_AUTHORIZATION'] 获取不到值的问题.

解决方法如下:

  • 如果已经开启rewrite_module模块,需要在httpd-vhosts.conf模块下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<VirtualHost *:80>
ServerName test.com
DocumentRoot "/data/www/"
<Directory "/data/www/">
# Laravel配置
Options Indexes FollowSymLinks
AllowOverride All
Order Deny,Allow
Require all granted
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# HTTP 基础认证需要添加下面两行
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</Directory>
</VirtualHost>
  • 如果没有开启rewrite_module模块,需要在入口处添加.htaccess文件,内容如下:
1
2
3
4
5
Options +FollowSymlinks -Multiviews
RewriteEngine On
#Authorization Headers
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
关注作者公众号,获取更多资源!
赏作者一杯咖啡~