AuthorizationCodeGrantService.php in OAuth2 Client 8.2
File
src/Service/Grant/AuthorizationCodeGrantService.php
View source
<?php
namespace Drupal\oauth2_client\Service\Grant;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\oauth2_client\PluginManager\Oauth2ClientPluginManagerInterface;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
class AuthorizationCodeGrantService extends Oauth2ClientGrantServiceBase {
protected $tempstore;
public function __construct(RequestStack $requestStack, StateInterface $state, UrlGeneratorInterface $urlGenerator, Oauth2ClientPluginManagerInterface $oauth2ClientPluginManager, PrivateTempStoreFactory $tempstoreFactory) {
parent::__construct($requestStack, $state, $urlGenerator, $oauth2ClientPluginManager);
$this->tempstore = $tempstoreFactory
->get('oauth2_client');
}
public function getAccessToken($clientId) {
$provider = $this
->getProvider($clientId);
if (!$this->currentRequest
->get('code')) {
$authorization_url = $provider
->getAuthorizationUrl();
$this->tempstore
->set('oauth2_client_state-' . $clientId, $provider
->getState());
$redirect = new RedirectResponse($authorization_url);
$redirect
->send();
exit;
}
elseif (!$this->currentRequest
->get('state') || $this->currentRequest
->get('state') !== $this->tempstore
->get('oauth2_client_state-' . $clientId)) {
$this->tempstore
->delete('oauth2_client_state-' . $clientId);
}
else {
try {
$accessToken = $provider
->getAccessToken('authorization_code', [
'code' => $this->currentRequest
->get('code'),
]);
$this
->storeAccessToken($clientId, $accessToken);
} catch (IdentityProviderException $e) {
watchdog_exception('OAuth2 Client', $e);
}
}
}
public function getGrantProvider($clientId) {
return $this
->getProvider($clientId);
}
}