Reputation: 14198
How can I add the authorization header in phpunit? I am testing a json api that requires an api_token. laravel docs provide a actingAs method. But this does not work in my case because the api token is not directly related to the users table.
EDIT:
public function test_returns_response_with_valid_request()
{
$response = $this->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
Upvotes: 14
Views: 28682
Reputation: 1
According to this documentations https://laravel.com/docs/5.8/api-authentication#passing-tokens-in-requests & https://laravel.com/docs/8.x/http-tests
There are several ways of passing the API token to your application. You may choose any of these approaches based on the needs of your application.
$response = $this->json('POST', '/api/sth?api_token='.$token, $test_data)->assertSussessful();
$response = $this->json('GET', '/api/sth', [
'headers' => [
'Accept' => 'application/json',
],
'form_params' => [
'api_token' => $token,
],
]);
$response = $this->json('GET', '/api/sth', [
'headers' => [
'Authorization' => 'Bearer '. $token,
'Accept' => 'application/json'
]
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '. $token,
'Accept' => 'application/json'
])->post('/api/sth', $test_data);
Upvotes: 0
Reputation: 101
You can use withHeader method and pass in your token, and this works on my local (Laravel 6)
public function test_returns_response_with_valid_request()
{
// define your $token here
$response = $this->withHeader('Authorization', 'Bearer ' . $token)
->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
Or you can use actingAs with look at docs here with api guard
public function test_returns_response_with_valid_request()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user, 'api')
->json('post', '/api/lookup', [
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
Upvotes: 10
Reputation: 479
According to documentation.
You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the
actingAs
method:$this->actingAs($user, 'api');
Upvotes: 33
Reputation: 58
According to documentation
public function test_returns_response_with_valid_request()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->post('/api/lookup',[
'email' => '[email protected]'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
Upvotes: 2