Search code examples
phplaravelhomesteadlaravel-passport

Retrieving client credentials grant tokens when using Homestead


I'm trying to use client credentials grant tokens for machine-to-machine authentication. I've got two separate sites (API & Web).

I've created a client credentials grant client on API.

php artisan passport:client --client

On Web, I'm trying to retrieve a token from API, using the below code. The PASSWORD_ID/PASSWORD_SECRET are stored in my .env file, I copied them directly from database so they're definitely correct.

$guzzle = new GuzzleHttp();
    $response = $guzzle->get('http://testsite-api.test/oauth/token', [
        'form_params' => [
            'grant_type' => 'client_credentials',
            'client_id' => env('PASSPORT_ID'),
            'client_secret' => env('PASSPORT_SECRET'),
        ],
    ]);

From this I am getting the following error:

Client error: POST http://testsite-api.test/oauth/token resulted in a 401 Unauthorized response: {"error":"invalid_client","error_description":"Client authentication failed","message":"Client authentication failed"}

Please note: I pulled this code onto my Mac (which uses valet) and it worked straight away.

I've used postman to test it, and it worked first time, using the same ID/SECRET used within Web.

Any ideas where I'm going wrong? I'm fairly certain it's a homestead issue, but I'm having trouble finding a resolve.


Solution

  • The issue might be with related with using env() function. If the config is cached with php artisan config:cache the env() function always returns null, you can test that by runing php artisan config:clear and trying to send request again, it should work just fine.

    Also you should refactor your app, the env() should only be used in config/ files, that way you can cache your variables and in you app simply use config('app.PASSPORT_SECRET'), app being the file name that the config is put it.