简体   繁体   中英

Can't test API endpoint with JWT token in Symfony

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.

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',
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM