AuthorizationCodeGrantService.php in OAuth2 Client 8.3
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\Core\Url;
use Drupal\oauth2_client\Plugin\Oauth2Client\Oauth2ClientPluginRedirectInterface;
use Drupal\oauth2_client\PluginManager\Oauth2ClientPluginManagerInterface;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessTokenInterface;
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($pluginId) {
$provider = $this
->getProvider($pluginId);
$authorization_url = $provider
->getAuthorizationUrl();
$this->tempstore
->set('oauth2_client_state-' . $pluginId, $provider
->getState());
if ($this->currentRequest
->hasSession()) {
$this->currentRequest
->getSession()
->save();
}
$redirect = new RedirectResponse($authorization_url);
$redirect
->send();
exit;
}
public function requestAccessToken($pluginId, $code) {
$provider = $this
->getProvider($pluginId);
try {
$accessToken = $provider
->getAccessToken('authorization_code', [
'code' => $code,
]);
if ($accessToken instanceof AccessTokenInterface) {
$this
->storeAccessToken($pluginId, $accessToken);
return TRUE;
}
} catch (IdentityProviderException $e) {
watchdog_exception('OAuth2 Client', $e);
}
return FALSE;
}
public function getGrantProvider($pluginId) {
return $this
->getProvider($pluginId);
}
public function getPostCaptureRedirect($pluginId) {
$clientPlugin = $this
->getClient($pluginId);
if ($clientPlugin instanceof Oauth2ClientPluginRedirectInterface) {
return $clientPlugin
->getPostCaptureRedirect();
}
$url = Url::fromRoute('oauth2_client.oauth2_client_plugin_list');
return new RedirectResponse($url
->toString(TRUE)
->getGeneratedUrl());
}
}