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

5.4k Views Asked by At

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

3

There are 3 best solutions below

10
On BEST ANSWER
 $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.

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

This is how to send a bearer token for example

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