samedi 27 juin 2020

How do I test authentication from a UI app to Laravel Passport?

My application authenticates just fine using the Nuxt OAuth module. However, when trying to test the same conditions, it fails. Here is my error:

{
  "error":"invalid_grant",
  "error_description":"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
  "hint":"",
  "message":"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}

This is the code for my test:

<?php
...
class LoginTest extends TestCase
{

    use RefreshDatabase, WithFaker;

    protected $user, $client, $accessToken, $oauth_access_tokens_table;
    public $mockConsoleOutput = false;

    public function setUp() : void
    {
        parent::setUp();

        $this->user = factory('App\User')->create(['password' => 'password']);

        $this->artisan('passport:install', [
            '--no-interaction' => true
        ]);
        $this->artisan('passport:keys', ['--no-interaction' => true]);

        $this->accessToken = $this->user->createToken('authToken')->accessToken;

        $this->client = DB::table('oauth_clients')->find(2); // password grant client
    }

    public function testAUserCanAuthenticateViaApi()
    {
        $client = Passport::actingAsClient($this->client, ['*']);

        $payload = [
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'username' => $this->user->email,
            'password' => 'password',
            'scope' => '',
        ];

        $headers = [
            'accept' => 'application/json, text/plain, */*',
        ];

        $response = $this->post('/oauth/token', $payload, $headers);

        $this->assertAuthenticatedAs($this->user);
    }
}

I can confirm that the client exists and that the data is there as it should be. I am sure that there is a better way to do this, but I have struggled for several hours and I feel that I am missing something fundamental. At this point, I am simply trying to successfully fetch a token. Thank you in advance for looking at this.

Aucun commentaire:

Enregistrer un commentaire