Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Laravel 5.3 protected API

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!

like image 372
DerJacques Avatar asked Mar 10 '23 22:03

DerJacques


2 Answers

A much easier solution is to add the api guard to the actingAs() method:

$this->actingAs($user, 'api');
like image 143
Jeroen Noten Avatar answered Mar 15 '23 18:03

Jeroen Noten


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.

like image 30
DerJacques Avatar answered Mar 15 '23 18:03

DerJacques