问题
I am passing an Authorization: Bearer { Token } as a HTTP request to my Symfony Rest Controller.
My Request:
GET /app_dev.php/api/members HTTP/1.1
Host: localhost
Authorization: Bearer 123456789
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Inside My controller:
$this->getRequest()->headers;
For some reason when I use Symfony's Request method the Authorization header isn't available to my controller. When I use PHP's getallheaders() the Authorization header shows up as expected. Any Ideas on why Symfony isn't seeing it?
Thanks
回答1:
It is most likely stripped by Apache. Bearer is not a known scheme, it is sort of proprietary.
Therefore, either you use a custom header, like X-Bearer-Token: 123456789 or you can try to add this rewrite condition in your .htaccess
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
回答2:
There seems to be a disconnect here between the question and the accepted answer. If the Authorization header is available to PHP's getallheaders() then Apache clearly isn't stripping it. I'd guess that the problem is related to the use of Symfony. $this->getRequest()->headers doesn't return an object containing headers, it returns a HeaderBag. Assuming the header is visible to getallheaders(), this works:
$this->getRequest()->headers->all();
Or more specifically:
$this->getRequest()->headers->get('Authorization');
回答3:
Symfony is using php global variable $_SERVER to create Request->headers variable, but $_SERVERdoes not contain all headers. For getting all headers you have to use php native function getallheaders() more info: http://php.net/manual/en/function.getallheaders.php
回答4:
seems like the apache mod_php "eats" the authorization header.
this worked for me:
if (!$request->headers->has('Authorization') && function_exists('apache_request_headers')) {
$all = apache_request_headers();
if (isset($all['Authorization'])) {
$request->headers->set('Authorization', $all['Authorization']);
}
}
回答5:
You can also use apache_request_headers(); to get the original headers which will have the Authorization header.
来源:https://stackoverflow.com/questions/19443718/symfony-2-3-getrequest-headers-not-showing-authorization-bearer-token