How to test authentication via API with Laravel Passport? How to test authentication via API with Laravel Passport? laravel laravel

How to test authentication via API with Laravel Passport?


This is how you can implement this, to make it actually work.

First of all, you should properly implement db:seeds and Passport installation.

Second one, you don't need, to create your own route to verify, if that works (basic Passport responses are fine enough, for that).

So here is a description, on how it worked in my installation (Laravel 5.5)...

In my case, I need only one Passport client, that's why, I created another route, for api authorization (api/v1/login), to only supply username and password. You can read more about it here.

Fortunately this example covers basic Passport authorization test also.

So to successfully run your tests, the basic idea is:

  1. Create passport keys on test setup.
  2. Seed db with users, roles and other resources which might be needed.
  3. Create .env entry with PASSPORT_CLIENT_ID (optional - Passport always create password grant token with id = 2 on empty db).
  4. Use this id to fetch proper client_secret from db.
  5. And then run your tests...

Code examples...

ApiLoginTest.php

/*** @group apilogintests*/    public function testApiLogin() {    $body = [        'username' => 'admin@admin.com',        'password' => 'admin'    ];    $this->json('POST','/api/v1/login',$body,['Accept' => 'application/json'])        ->assertStatus(200)        ->assertJsonStructure(['token_type','expires_in','access_token','refresh_token']);}/** * @group apilogintests */public function testOauthLogin() {    $oauth_client_id = env('PASSPORT_CLIENT_ID');    $oauth_client = OauthClients::findOrFail($oauth_client_id);    $body = [        'username' => 'admin@admin.com',        'password' => 'admin',        'client_id' => $oauth_client_id,        'client_secret' => $oauth_client->secret,        'grant_type' => 'password',        'scope' => '*'    ];    $this->json('POST','/oauth/token',$body,['Accept' => 'application/json'])        ->assertStatus(200)        ->assertJsonStructure(['token_type','expires_in','access_token','refresh_token']);}

Notes:

Credentials need to be modified of course.

PASSPORT_CLIENT_ID needs to be 2, as explained before.

JsonStructure verification is redundant, since we get 200 response, only if authorization succeeds. However, if you wanted additional verification, this also passes...

TestCase.php

public function setUp() {    parent::setUp();    \Artisan::call('migrate',['-vvv' => true]);    \Artisan::call('passport:install',['-vvv' => true]);    \Artisan::call('db:seed',['-vvv' => true]);}

Notes:

Here we are creating relevant entries to db, which are needed in our tests.So remember, to have users with roles etc. seeded here.

Final notes...

This should be enough, to get your code working. On my system, all this passes green and also works on my gitlab CI runner.

Finally, please check your middlewares on routes also. Especially, if you were experimenting with dingo (or jwt by thymon) package.

The only middleware, you may consider, applying to Passport authorization route, is throttle to have some protection from brute force attack.

Side note...

Passport and dingo have totally different jwt implementations.

In my tests, only Passport behaves the right way and I assume, that this is the reason, why dingo is not maintained anymore.

Hope it will solve your problem...


Laravel Passport actually ships with some testing helpers which you can use to test your authenticated API endpoints.

Passport::actingAs(    factory(User::class)->create(),);


I think the selected answer is likely the most robust and best here so far, but I wanted to provide an alternative that worked for me if you just need to quickly get tests passing behind passport without a lot of setup.

Important note: I think if you're going to do a lot of this, this isn't the right way and other answers are better. But in my estimation this does seem to just work

Here's a full test case where I need to assume a user, POST to an endpoint, and use their Authorization token to make the request.

<?phpnamespace Tests\Feature;use Tests\TestCase;use Illuminate\Foundation\Testing\WithFaker;use Illuminate\Foundation\Testing\RefreshDatabase;use App\Models\User;use Laravel\Passport\Passport;class MyTest extends TestCase{    use WithFaker, RefreshDatabase;    public function my_test()    {        /**        *        * Without Artisan call you will get a passport         * "please create a personal access client" error        */        \Artisan::call('passport:install');        $user = factory(User::class)->create();        Passport::actingAs($user);        //See Below        $token = $user->generateToken();        $headers = [ 'Authorization' => 'Bearer $token'];        $payload = [            //...        ];        $response = $this->json('POST', '/api/resource', $payload, $headers);        $response->assertStatus(200)                ->assertJson([                    //...                ]);    }}

And for clarity, here is the generateToken() method in the User model, which leverages the HasApiTokens trait.

public function generateToken() {    return $this->createToken('my-oauth-client-name')->accessToken; }

This is fairly rough and ready in my opinion. For example it if you're using the RefreshDatabase trait you have to run the passport:install command like this in every method. There may be a better way to do this via global setup, but I'm fairly new to PHPUnit so this is how I'm doing it (for now).