Search code examples
symfonyfunctional-testing

Symfony 2 controller test can't pass Authorization header


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

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

In the test controller:

$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 );

Output:

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
        (
        )

)

How can I pass in the Authorization header?


Solution

  • 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 );
    

    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