我有一个用 Symfony 2 编写的 HTTP API,我正在为它编写一些功能测试。
我注意到当我尝试发送 Authorization
当我记录收到的 header 时, Controller 中没有收到 header 。
在测试 Controller 中:
$client = self::createClient();
$client->insulate();
$headers = array(
'Authorization' => "Bearer {$accessToken}",
'CONTENT_TYPE' => 'application/json',
);
$client->request('DELETE', "/auth", array(), array(), $headers );
在测试的 Controller 中:
print_r( $request->headers );
输出:
Symfony\Component\HttpFoundation\HeaderBag Object
(
[headers:protected] => Array
(
[host] => Array
(
[0] => localhost
)
[user-agent] => Array
(
[0] => Symfony2 BrowserKit
)
[accept] => Array
(
[0] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
)
[accept-language] => Array
(
[0] => en-us,en;q=0.5
)
[accept-charset] => Array
(
[0] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
)
[content-type] => Array
(
[0] => application/json
)
[x-php-ob-level] => Array
(
[0] => 0
)
)
[cacheControl:protected] => Array
(
)
)
我怎样才能通过
Authorization
标题?
最佳答案
对于 Symfony 2,您似乎需要使用 $_SERVER
中概述的标题。文档 [1]。
这在文档中不是很清楚,但就我而言,我必须执行以下操作:
$headers = array(
'HTTP_AUTHORIZATION' => "Bearer {$accessToken}",
'CONTENT_TYPE' => 'application/json',
);
$client->request('DELETE', "/auth", array(), array(), $headers );
注意
HTTP_AUTHORIZATION
对比 Authorization
问题中使用的标题。这为我解决了这个问题。[1] http://www.php.net/manual/en/reserved.variables.server.php
关于Symfony 2 Controller 测试无法通过授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21253376/