Search code examples
laravelapilaravel-passport

Return the access token and the user when authenticating using Passport and Laravel


I am creating an API using Laravel 5.4 and Passport. The API authorization is done using Password grant type.

Below is a sample request:

$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
  'form_params' => [
     'grant_type' => 'password',
     'client_id' => 'client-id',
     'client_secret' => 'client-secret',
     'username' => 'taylor@laravel.com',
     'password' => 'my-password',
     'scope' => '',
   ],
]);

return json_decode((string) $response->getBody(), true);

This will send a POST request to '/oauth/token' with the following response:

{
  "token_type": "Bearer",
  "expires_in": 3155673600,
  "access_token": "eyJ0eXAiOiJK...",
  "refresh_token": "LbxXGlD2s..."
}

What I want is to get a response including the authenticated user as shown below:

[
  data:{
     name: Jhon,
     email: jhon@example.com,
     address: ASDF Street no.23
  },
  token{
     "token_type": "Bearer",
     "expires_in": 3155673600,
     "access_token": "eyJ0eXAiOiJK...",
     "refresh_token": "LbxXGlD2s..."
  }
]

What I already did was alter the PasswordGrant file at line 65

vendor/league/oauth2-server/src/Grant/PasswordGrant.php

$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
return $responseType;

I hope someone can help me, and tell me how to resolve this, thank you.


Solution

  • You could write an (after-) middleware that takes the original response and transforms it to be the way you want it to be. But be aware that all other Passport middleware (CheckClientCredentials, CheckScopes, CreateFreshApiToken, etc...) probably depends on that specific format and will have to be adapted as well.