oauth2-bundle
oauth2-bundle copied to clipboard
[Question] How to manually generate a refresh token?
Hi,
for a special case I need to manually generate an access and a refresh token with the bundle. The reason is very complicated, but I have to automatically generate a user on the first request of a device. So, I have no user and no registration.
I managed to get an access token by the following code, but I don't know how I can get the refresh token. I searched for the methods in the code of the bundle but by now I couldn´t find the right methods. How can I generate a refresh token manually?
I hope you can help. Thank you very much!
use Trikoder\Bundle\OAuth2Bundle\League\Entity\AccessToken as AccessTokenEntity;
use Trikoder\Bundle\OAuth2Bundle\League\Entity\Client as ClientEntity;
use Trikoder\Bundle\OAuth2Bundle\League\Entity\Scope as ScopeEntity;
use Trikoder\Bundle\OAuth2Bundle\Model\AccessToken as AccessTokenModel;
use Trikoder\Bundle\OAuth2Bundle\Model\Client as ClientModel;
private function createAuthToken($user, $client = 'apps') {
$clientModel = $this->em->getRepository(ClientModel::class)->findOneBy(['identifier' => $client]);
$now = new \DateTimeImmutable();
$accessTokenTtl = (new \DateTimeImmutable())->add(new \DateInterval(self::ACCESS_TOKEN_TTL));
$expiresIn = $accessTokenTtl->getTimestamp() - $now->getTimestamp() - 3600;
$accessTokenModel = new AccessTokenModel(bin2hex(random_bytes(40)), $accessTokenTtl, $clientModel, $user->getEmail(), []);
$privateKey = new CryptKey($this->privateKey, null, false);
$clientEntity = new ClientEntity();
$clientEntity->setIdentifier($accessTokenModel->getClient()->getIdentifier());
$clientEntity->setRedirectUri(array_map('strval', $accessTokenModel->getClient()->getRedirectUris()));
$accessTokenEntity = new AccessTokenEntity();
$accessTokenEntity->setPrivateKey($privateKey);
$accessTokenEntity->setIdentifier($accessTokenModel->getIdentifier());
$accessTokenEntity->setExpiryDateTime($accessTokenModel->getExpiry());
$accessTokenEntity->setClient($clientEntity);
$accessTokenEntity->setUserIdentifier($accessTokenModel->getUserIdentifier());
foreach ($accessTokenModel->getScopes() as $scope) {
$scopeEntity = new ScopeEntity();
$scopeEntity->setIdentifier((string)$scope);
$accessTokenEntity->addScope($scopeEntity);
}
$this->em->persist($accessTokenModel);
$response = [
'token_type' => 'Bearer',
'expires_in' => $expiresIn,
'access_token' => $accessTokenEntity->__toString(),
'refresh_token' => null,
];
return $response;
}