Symfony 2控制器测试无法通过授权标头 [英] Symfony 2 controller test can't pass Authorization header

查看:65
本文介绍了Symfony 2控制器测试无法通过授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Symfony 2编写的HTTP API,并且正在为此编写一些功能测试.

I have an HTTP API written in Symfony 2 and I'm writing some functional tests for it.

我注意到当我尝试发送Authorization标头时,当我记录接收到的标头时,控制器中没有收到它.

I noticed that when I try to send an Authorization header it is not received in the controller when I log the received headers.

在测试控制器中:

$client = self::createClient();
$client->insulate();

$headers = array(
    'Authorization' => "Bearer {$accessToken}",
    'CONTENT_TYPE' => 'application/json',
);

$client->request('DELETE', "/auth", array(), array(), $headers );

在经过测试的控制器中:

In the tested 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]中概述的标头.

It seems that for Symfony 2 you need to use the headers which are outlined in the $_SERVER documentation [1].

从文档中并不清楚,但是就我而言,我必须执行以下操作:

This wasn't very clear from the documentation but in my case I had to do the following:

$headers = array(
    'HTTP_AUTHORIZATION' => "Bearer {$accessToken}",
    'CONTENT_TYPE' => 'application/json',
);

$client->request('DELETE', "/auth", array(), array(), $headers );

请注意问题中使用的HTTP_AUTHORIZATION vs Authorization标头.这为我解决了这个问题.

Notice the HTTP_AUTHORIZATION vs Authorization header used in the question. This fixed the issue for me.

[1] http://www.php.net/manual/en/reserved. variables.server.php

这篇关于Symfony 2控制器测试无法通过授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆