Skip to content

Instantly share code, notes, and snippets.

@drakakisgeo
Last active August 29, 2022 02:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save drakakisgeo/48dcab1539612c82449b9757940ac7ee to your computer and use it in GitHub Desktop.
Save drakakisgeo/48dcab1539612c82449b9757940ac7ee to your computer and use it in GitHub Desktop.
Print Access Token from Laravel Passport
<?php
namespace App\Traits;
use App\User;
use DateTime;
use GuzzleHttp\Psr7\Response;
use Illuminate\Events\Dispatcher;
use Laravel\Passport\Bridge\AccessToken;
use Laravel\Passport\Bridge\AccessTokenRepository;
use Laravel\Passport\Bridge\Client;
use Laravel\Passport\Bridge\RefreshToken;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
# All glory goes to this person @ this comment https://github.com/laravel/passport/issues/71#issuecomment-330506407
# I just did some modifications in order to fetch the tokens from the database and not generate new ones each time.
/**
* Trait PassportToken
*
* @package App\Traits
*/
trait PassportTokenPrint
{
protected function fetchPassportTokenByUser(User $user, $clientId, $token)
{
$accessToken = new AccessToken($user->id);
$accessToken->setIdentifier($token->id);
$accessToken->setClient(new Client($clientId, null, null));
$accessToken->setExpiryDateTime(new DateTime($token->expires_at));
$refreshToken = new RefreshToken();
$refreshToken->setAccessToken($accessToken);
$refreshToken->setExpiryDateTime(new DateTime($token->expires_at));
return [
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
];
}
protected function sendBearerTokenResponse($accessToken, $refreshToken)
{
$response = new BearerTokenResponse();
$response->setAccessToken($accessToken);
$response->setRefreshToken($refreshToken);
$privateKey = new CryptKey('file://' . Passport::keyPath('oauth-private.key'));
$response->setPrivateKey($privateKey);
$response->setEncryptionKey(app('encrypter')->getKey());
return $response->generateHttpResponse(new Response);
}
/**
* @param \App\Entities\User $user
* @param $clientId
* @param bool $output default = true
* @return array | \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
*/
protected function fetchAccessTokenForClient(User $user, $clientId, $token, $output = true)
{
$passportToken = $this->fetchPassportTokenByUser($user, $clientId, $token);
$bearerToken = $this->sendBearerTokenResponse($passportToken['access_token'], $passportToken['refresh_token']);
if (!$output) {
$bearerToken = json_decode($bearerToken->getBody()->__toString(), true);
}
return $bearerToken;
}
protected function clientAccessToken(User $user, $clientId, $token){
return $this->fetchAccessTokenForClient($user, $clientId, $token, false)['access_token'];
}
}
@drakakisgeo
Copy link
Author

drakakisgeo commented May 4, 2018

You use the trait and you do $this->fetchAccessTokenForClient($user, $clientId, $tokenId, false) and you get the following result:

array:4 [
  "token_type" => "Bearer"
  "expires_in" => 31532183
  "access_token" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4MDQxMGY5OTlkODRmYzllOWY4MWEyOTA0NzBlMDc2YjI5YjlmYjNmNTY3NTBmN2QxOGJkZjU0OTg3NzQ5NjE1OTMwMzVhMzBjMzdhODA3In0.eyJh "
  "refresh_token" => "def50200bdae3a7639a12fee90d24ae035907ce71fb585a6c2292ed7dc3421cb9331fd6159bedcc31f16bb909433ef4570dd3ca7dd18bdc315cc464f94d02802db262f7c3fed8c141e2b812415e69a79 "
]

@georgecpacheco
Copy link

Hi!
I'm trying use your Trait, but i don't know how to get $token parameter, this give me a error:
"Trying to get property 'id' of non-object"
If you can help me, thanks!

@triblex
Copy link

triblex commented Sep 13, 2018

Hello, when i use this what do i need to fill in as the $token parameter? I've tried the access token ID but i only get error:
ErrorException: Trying to get property of non-object in file ...\app\Traits\PassportTokenPrint.php on line 36.
Thank you

@mohammadjavad79
Copy link

Hi
i'm trying to use your trait but it return an error that i could'nt solve . can you help me please ?

error message : "Too few arguments to function Laravel\Passport\Bridge\AccessToken::__construct(), 1 passed in D:\program\xamp\htdocs\jobaro\app\Http\Controllers\v1\traits\PassportTokenPrint.php on line 37 and exactly 3 expected"

note:i passed some others argument ( $accessToken = new AccessToken($user->id,['customer'],$user);) but it returns another error message
new error message "Laravel\Passport\Bridge\AccessToken::__construct(): Argument #3 ($client) must be of type League\OAuth2\Server\Entities\ClientEntityInterface, App\Models\Customer given, called in D:\program\xamp\htdocs\jobaro\app\Http\Controllers\v1\traits\PassportTokenPrint.php on line 37"

note2:i am using laravel 8

@cbqi
Copy link

cbqi commented Aug 29, 2022

Hello,i use this,but i get many different tokens,and they are useful,why happend to this ,they're not the ones I started with

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment