2

I'm having some troubles when testing my endpoint with Phpunit and Symfony. The thing is I'm able to authenticate correctly when using nelmio api doc for making tests, with postman, or even from the client side which is in android.

But when I', trying to test the endpoint with phpunit I get 401 Unauthorized message.

Here is the request that I make from the functional test in phpunit:

$this->client->request('POST', '/api/v1/recipes',$data,array(),array(),$header);

And here is the content of the header:

$header = array(
        'Authorization'=> 'Bearer '.$token,
        'CONTENT_TYPE' => 'application/json',
    );

I also tried with HTTP_AUTHORIZATION key, but is not working either.

I use the built-in Symfony server, I'm not sure if that is important, because I've seen some other issues when using headers and working under Apache.

By the way, the token is correctly formed as I double-checked with jwt.io online decoder.

I'm kind of desperate, any help would be great.

Jotaeme
  • 345
  • 1
  • 6
  • 16

1 Answers1

1

try to change this:

$header = array(
    'Authorization'=> 'Bearer '.$token,
    'CONTENT_TYPE' => 'application/json',
);

to this:

$header = array(
   'HTTP_Authorization' => sprintf('%s %s', 'Bearer', $token),
   'HTTP_CONTENT_TYPE' => 'application/json',
   'HTTP_ACCEPT'       => 'application/json',
);
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
  • 1
    When I make the request from the android client, postman, etc... I get none. But when I tried to make a functional test with phpunit I get 401 Unauthorized error – Jotaeme Jun 29 '17 at 19:24
  • Beautiful answer, works for laravel as well when you want to make requests as a user without using the `actingAs` method. – Ghustavh Ehm Nov 12 '21 at 21:27