FilipeAntunes's avatar

Passport "oauth/token" Password Grant Client : testing swtich to wrong DB

I have 2 environments defined with an ".env" file and another one ".env.testing".

(important) Each environment uses a different database:

example ".env"

DB_DATABASE=larvel_prod

example ".env.testing"

DB_DATABASE=larvel_testing

When I use Postman the authentication works. However when I test with PHPUnit. I have strange problems.

In any case, I use these parameters:

$params = [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => '[email protected]',
    'password' => 'my-password',
    'scope' => '',
]

So with the snippet below, it works with Postman:

$response = Http::asForm()->post('http://passport-app.test/oauth/token', $params);
return $response->json();

But not with PHPUnit! I got this error:

Client authentication failed

If I debug a bit, my tests start with the "larval_testing" database and when Passport retrieves the passport client from her ID (select * from oauth_clients where id=??), I notice that the base is no longer "larval_testing", but "larvel_prod"! So with the prod base and of course with the wrong "client_secret" and "client_id".

Another attempt with this code:

$response = Request::create('http://passport-app.test/oauth/token', 'POST', $params);
return Route::dispatch($response);

It doesn't work. Neither with Postman nor with PHPUnit. I have this error:

The authorization grant type is not supported by the authorization server.

config summary:

  • laravel: 10.10
  • passport: 11.9

Thanks in advance for any help.

0 likes
2 replies
s4muel's avatar

have a look here: https://laravel.com/docs/10.x/http-tests#making-requests and use $this->post() ( or $this->get()) in your tests instead of Request::create() .

These methods do not actually issue a "real" HTTP request to your application. Instead, the entire network request is simulated internally.

the Request in your case did a request to the application as if you would via browser for example. so not to testing environment, even if called from test. but it is not the same thing.

Please or to participate in this conversation.