How to fetch token for Laravel REST API?

59 Views Asked by At

I am using Laravel 6.4 version and trying to get tokens using following code.

$http = new \GuzzleHttp\Client();
try {
    $tokenResponse = $http->post('http://127.0.0.1:8000/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => $client->id,
            'client_secret' => $client->secret,
            'username' => $request->email,
            'password' => $request->password,
            //'scope'         => '*',
        ],
    ]);
} catch (\Exception $e) {
    // Handle exception
    dd($e->getMessage());
} 

But it does not return anything and also does not provide the exception. The process is just in a continuous running state and never completed. Also, I have tried directly to call http://127.0.0.1:8000/oauth/token using Postman, and it seems to be working fine and providing me the user with an access token as well. Can anyone suggest how I can debug it to get what errors there are?

I had tried to add a try-catch statement to get an exception so I can get an error message, but it does not provide me anything.

1

There are 1 best solutions below

0
Raju Mondal On

Use GuzzleHttp Exception Handling:

GuzzleHttp may throw exceptions in certain error scenarios. Modify your catch block to handle GuzzleHttp exceptions and log the details:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

try {
    $http = new Client([
        'timeout' => 30,
    ]);

    $tokenResponse = $http->post('http://127.0.0.1:8000/oauth/token', [
        'form_params' => [
            'grant_type'    => 'password',
            'client_id'     => $client->id,
            'client_secret' => $client->secret,
            'username'      => $request->email,
            'password'      => $request->password,
        ],
    ]);
    
    $tokenData = json_decode($tokenResponse->getBody(), true);

    // Now you can access the token data
    $accessToken = $tokenData['access_token'];

} catch (RequestException $e) {
    if ($e->hasResponse()) {
        // If the server responded with an error, you can get the error message
        $errorResponse = json_decode($e->getResponse()->getBody(), true);
        dd($errorResponse);
    } else {
        // If there was no response from the server
        dd($e->getMessage());
    }
} catch (\Exception $e) {
    dd($e->getMessage());
}