phpsymfonyphpunitliipfunctionaltestbundle

How to pass bearer token to test API using phpunit and Liip


this is what I am doing

I make a first call to get the token

$client->request('POST', '/api/login_check', [], [],
        ['CONTENT_TYPE' => 'application/json'],
        json_encode(
            [
                "username" => $user->getUsername(),
                "password" => 'password',
            ]
        )
    );

    $response = $client->getResponse();
    return json_decode($response->getContent())->token;

then a second one to use it

        $client->request('GET', '/api/my_endpoint', [], [], [
            'headers' => [
                'Authorization' => $token
            ]
        ]);

$token is a valid token (tested using postman) like 'Bearer SUPERLONGSTRING' but I am getting the error message

JWT Token not found

thanks


Solution

  • $client->request('GET', '/api/my_endpoint', [], [], [
         'HTTP_AUTHORIZATION' => "{$token}",
         'CONTENT_TYPE' => 'application/ld+json',
         'HTTP_ACCEPT' => 'application/ld+json'
    ]);
    

    You should use the HTTP_AUTHORIZATION header for that. Try above code. Also you don't need a nested array for headers.

    Also since we don't see the format of your token keep in mind that the bearer format is:

    Bearer (space) the rest of the token.