public function AuthorizationCodeGrantService::getAccessToken in OAuth2 Client 8.2
Same name and namespace in other branches
- 8.3 src/Service/Grant/AuthorizationCodeGrantService.php \Drupal\oauth2_client\Service\Grant\AuthorizationCodeGrantService::getAccessToken()
Get an OAuth2 access token.
Parameters
string $clientId: The plugin ID of the OAuth2 Client plugin for which an access token should be retrieved.
Overrides Oauth2ClientGrantServiceInterface::getAccessToken
File
- src/
Service/ Grant/ AuthorizationCodeGrantService.php, line 54
Class
- AuthorizationCodeGrantService
- Handles Authorization Grants for the OAuth2 Client module.
Namespace
Drupal\oauth2_client\Service\GrantCode
public function getAccessToken($clientId) {
$provider = $this
->getProvider($clientId);
// If an authorization code is not set in the URL parameters, get one.
if (!$this->currentRequest
->get('code')) {
// Get the authorization URL. This also generates the state.
$authorization_url = $provider
->getAuthorizationUrl();
// Save the state to Drupal's tempstore.
$this->tempstore
->set('oauth2_client_state-' . $clientId, $provider
->getState());
// Redirect to the authorization URL.
$redirect = new RedirectResponse($authorization_url);
$redirect
->send();
exit;
}
elseif (!$this->currentRequest
->get('state') || $this->currentRequest
->get('state') !== $this->tempstore
->get('oauth2_client_state-' . $clientId)) {
// Potential CSRF attack. Bail out.
$this->tempstore
->delete('oauth2_client_state-' . $clientId);
}
else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider
->getAccessToken('authorization_code', [
'code' => $this->currentRequest
->get('code'),
]);
$this
->storeAccessToken($clientId, $accessToken);
} catch (IdentityProviderException $e) {
watchdog_exception('OAuth2 Client', $e);
}
}
}