I have just set up a small Laravel API that is protected via Passport that was introduced in 5.3. So far, everything is working well.
Since I will be the only one consuming the API, I simply added \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
to my web middleware-group in order to generate and handle my API tokens.
To my question: How may I handle tokens in my application tests? actingAs($user)
does not seem to magically add the user's token to the request. I can use $this->withoutMiddleware();
, but then all middleware is disabled, and not only the one responsible for authentication.
Any ideas on how to solve this?
Thank you very much for you help!
A much easier solution is to add the api
guard to the actingAs()
method:
$this->actingAs($user, 'api');
I finally made it work by building upon on this answer: https://laracasts.com/discuss/channels/testing/passport-personal-access-token-unit-test
Copy pasted from the author of above-mentioned post:
/**
*@test
*/
public function Create_an_access_token()
{
$clientRepository = new ClientRepository();
$client = $clientRepository->createPersonalAccessClient(
null, 'Test Personal Access Client', 'http://localhost'
);
DB::table('oauth_personal_access_clients')->insert([
'client_id' => $client->id,
'created_at' => new DateTime,
'updated_at' => new DateTime,
]);
$user = factory(User::class)->create();
$token = $user->createToken('TestToken')->accessToken;
$header = [];
$header['Accept'] = 'application/json';
$header['Authorization'] = 'Bearer '.$token;
$this->json('GET', '/api/user', [], $header)
->seeJson([
'id' => $user->id,
'email' => $user->email,
'name' => $user->name,
]);
}
I extracted the relevant and reusable parts into a small helper-class, and now the testing-code is rather short and readable.
Hope this helps someone in a similar situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With