Skip to content

Instantly share code, notes, and snippets.

@iflamed
Last active April 4, 2018 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iflamed/5278b8366a90c3f3ae13e57cd9b6f345 to your computer and use it in GitHub Desktop.
Save iflamed/5278b8366a90c3f3ae13e57cd9b6f345 to your computer and use it in GitHub Desktop.
Laravel Passport Generate Access_token By User Model
<?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\RefreshTokenRepository;
use Laravel\Passport\Bridge\Scope;
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;
// https://github.com/laravel/passport/issues/71
/**
* Trait PassportToken.
*/
trait PassportToken
{
/**
* Generate a new unique identifier.
*
* @param int $length
*
* @throws OAuthServerException
*
* @return string
*/
private function generateUniqueIdentifier($length = 40)
{
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (\TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred');
} catch (\Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string');
}
// @codeCoverageIgnoreEnd
}
private function issueRefreshToken(AccessTokenEntityInterface $accessToken)
{
$maxGenerationAttempts = 10;
$refreshTokenRepository = app(RefreshTokenRepository::class);
$refreshToken = $refreshTokenRepository->getNewRefreshToken();
$refreshToken->setExpiryDateTime((new \DateTime())->add(Passport::refreshTokensExpireIn()));
$refreshToken->setAccessToken($accessToken);
while ($maxGenerationAttempts-- > 0) {
$refreshToken->setIdentifier($this->generateUniqueIdentifier());
try {
$refreshTokenRepository->persistNewRefreshToken($refreshToken);
return $refreshToken;
} catch (UniqueTokenIdentifierConstraintViolationException $e) {
if ($maxGenerationAttempts === 0) {
throw $e;
}
}
}
}
protected function createPassportTokenByUser(User $user, $clientId, $tokenScopes = [])
{
$scopes = [];
if (is_array($tokenScopes)) {
foreach ($tokenScopes as $scope) {
$scopes[] = new Scope($scope);
}
}
$accessToken = new AccessToken($user->id, $scopes);
$accessToken->setIdentifier($this->generateUniqueIdentifier());
$accessToken->setClient(new Client($clientId, null, null));
$accessToken->setExpiryDateTime((new DateTime())->add(Passport::tokensExpireIn()));
$accessTokenRepository = new AccessTokenRepository(new TokenRepository(), new Dispatcher());
$accessTokenRepository->persistNewAccessToken($accessToken);
$refreshToken = $this->issueRefreshToken($accessToken);
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'), null, false);
$response->setPrivateKey($privateKey);
$response->setEncryptionKey(app('encrypter')->getKey());
return $response->generateHttpResponse(new Response());
}
/**
* @param \App\User $user
* @param $clientId
* @param array $scopes default = []
*
* @return array | \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
*/
public function getBearerTokenByUser(User $user, $clientId, $scopes = [])
{
$passportToken = $this->createPassportTokenByUser($user, $clientId, $scopes);
$bearerToken = $this->sendBearerTokenResponse($passportToken['access_token'], $passportToken['refresh_token']);
return json_decode($bearerToken->getBody()->__toString(), true);
}
}
@iflamed
Copy link
Author

iflamed commented Apr 4, 2018

how to use

$user = User::find(1);
$client_id = 11001001;
$scopes = ['*'];
// return array
return $this->getBearerTokenByUser($user, $client_id, $scopes);

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