Handle OAuth 2.0 Flow
@return BaseOAuth20
324573
public function handle()
	{
		// Get Var Elements
		$accessToken = $this->getAccessToken();

		$state = $this->getVar("state");
		
		// Initiate OAuth Client with Specific server configuration
		$to = new $this->_className();

		// Try to Handle the Authentication Process
		if ($accessToken == "")
		{
			$code = $this->_context->get("code");
			
			// If not received the "Code" Parameter, initiate the autorization request
			if ($code == "")
			{
				$state = md5(uniqid(rand(), TRUE)); //CSRF protection
				$this->setVar("state", $state);
				
				$params = array(
					"client_id" => $this->_client_id,
					"redirect_uri" => $this->_redirect_uri,
					"state" => $state,
					"scope" => $this->_scope
				);

				if (count($this->_extraArgs) > 0)
				{
					$params = array_merge($params, $this->_extraArgs);
				}
				
				$req = new WebRequest($to->authorizationURL());
				$req->redirect($params, $this->_window_top);
			}
			
			// Request the Access Token
			if ($this->_context->get("state") == $this->getVar("state"))
			{
				$params = array(
					"client_id" => $this->_client_id,
					"redirect_uri" => $this->_redirect_uri,
					"client_secret" => $this->_client_secret,
					"code" => $code,
					"grant_type" => "authorization_code"
				);
				
				$req = new WebRequest($to->accessTokenURL());
				$result = $req->post($params);

				$accessToken = $to->decodeAccessToken($result);
				
				$this->setVar("access_token", $accessToken);
				$to->setAccessToken($accessToken);
				
				$this->saveAccessToken();
				
				if ($this->_app_uri != "")
				{
					$req = new WebRequest($this->_app_uri);
					$response = $req->redirect();
				}
			}
		}
		else 
		{
			$to->setAccessToken($this->getVar('access_token'));
		}
		
		return $to;
		
	}
968775
public function getAuth(): ?Guard
    {
        if (!$this->hasAuth()) {
            $this->setAuth($this->getDefaultAuth());
        }
        return $this->auth;
    }
296352
public function getAuthenticationClient()
    {
        if (null === $this->authenticationClient) {
            $this->authenticationClient = new Auth\OAuth2(
                $this->getHttpClient(),
                $this->getOption('client_id'),
                $this->getOption('client_secret')
            );
        }

        return $this->authenticationClient;
    }
844463
public function canOauthorize()
    {
        $api = $this->getAPI();
        
        if ($api && $this->actor) {
            return $api->canAddService($this->actor);
        }

        return !is_null($api);
    }
36712
public function validateAuth()
    {
        // Send a get request to the API
        $response = $this->uniRequest->get(implode([$this->authURL, 'validate/']), $this->headers);
        // Check that we get 20X back
        if (in_array($response->code, $this->validCodes)) {
            // Return the response
            return $response;
        } else {
            // If we did not get 20X throw an exception
            throw new Exception($response->body->message, $response->code);
        }
    }
925696
public function actionConnectStep2()
    {
        $providerHandle = craft()->httpSession->get('oauth.console.providerHandle');
        $referer = craft()->httpSession->get('oauth.console.referer');


        // connect

        $provider = craft()->oauth->getProvider($providerHandle);

        if($response = craft()->oauth->connect(array(
            'plugin' => 'oauth',
            'provider' => $providerHandle
        )))
        {
            if($response['success'])
            {
                // token
                $token = $response['token'];

                $tokenArray = OauthHelper::tokenToArray($token);

                // save token
                craft()->httpSession->add('oauth.console.token.'.$providerHandle, $tokenArray);

                // session notice
                craft()->userSession->setNotice(Craft::t("Connected."));
            }
            else
            {
                craft()->userSession->setError(Craft::t($response['errorMsg']));
            }
        }
        else
        {
            // session error
            craft()->userSession->setError(Craft::t("Couldn’t connect"));
        }

        // redirect
        $this->redirect($referer);
    }
825818
public function authorizationEndpoint() {
		$endpoint = $this->getset('authorization_endpoint', func_get_args());
		return $this->validateEndpoint($endpoint ?: self::URI_AUTHORIZE);
	}
167715
public function token()
    {
        // Handle the token request
        $response = $this->tokenServer->handleTokenRequest(\OAuth2\Request::createFromGlobals());

        // Get the data as json and convert it to an array,
        // - so we can set our own response type.
        $data = $response->getResponseBody('json');
        $data = json_decode($data, true);

        // Set the response, status code and output content setting final output to true
        $this->response = $data;
        $this->statusCode = $response->getStatusCode();
        $this->output(true);
        return $this;
    }
715071
public function linkAccountCallback() {
    $sdk = $this->getSdk();

    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }

    $network_manager = $this->networkManager->createInstance('social_auth_twitter');
    $data_handler = $network_manager->getDataHandler();

    // Get the Twitter OAuth token from storage.
    if (!($oauth_token = $data_handler->get('oauth_token')) || !($oauth_token_secret = $data_handler->get('oauth_token_secret'))) {
      drupal_set_message($this->t('Twitter login failed. Token or Token Secret is not valid.'), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    $this->authManager->setSdk($sdk);
    $this->authManager->setAccessToken([
      'oauth_token' => $oauth_token,
      'oauth_token_secret' => $oauth_token_secret,
    ]);

    // Get the permanent access token.
    $access_token = $sdk->oauth('oauth/access_token', [
      'oauth_verifier' => $this->request->get('oauth_verifier'),
    ]);

    $this->authManager->setAccessToken([
      'oauth_token' => $access_token['oauth_token'],
      'oauth_token_secret' => $access_token['oauth_token_secret'],
    ]);

    // Get user's profile from Twitter API.
    if (!($this->authManager->getProfile()) || !($account_id = $this->authManager->getAccountId())) {
      drupal_set_message($this->t('@network login failed, could not load @network profile. Contact site administrator.', [
        '@network' => $this->t('Twitter'),
      ]), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    // Check whether any another user account already connected.
    $account = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties(['twitter_id' => $account_id]);
    $account = current($account);

    // Check whether another account was connected to this Twitter account.
    if ($account && (int) $account->id() !== (int) $this->currentUser()->id()) {
      drupal_set_message($this->t('Your @network account has already connected to another account on this site.', [
        '@network' => $this->t('Twitter'),
      ]), 'warning');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    $account = User::load($this->currentUser()->id());
    $account->get('twitter_id')->setValue($account_id);
    $account->save();

    drupal_set_message($this->t('You are now able to log in with @network', [
      '@network' => $this->t('Twitter'),
    ]));
    return $this->redirect('entity.user.edit_form', [
      'user' => $account->id(),
    ]);
  }
248020
protected function defaultBaseAuthUrl()
    {
        $baseAuthUrl = [
            Yii::$app->controller->getRoute()
        ];
        $params = $_GET;
        unset($params[$this->clientIdGetParamName]);
        $baseAuthUrl = array_merge($baseAuthUrl, $params);

        return $baseAuthUrl;
    }
76427
public function revoke()
    {
        $accessToken = $this->tokenRepo->get();
        $url = $this->credentials['loginURL'].'/services/oauth2/revoke';

        $options['headers']['content-type'] = 'application/x-www-form-urlencoded';
        $options['form_params']['token'] = $accessToken;

        return $this->httpClient->request('post', $url, $options);
    }
29872
public function connectAction()
    {
        // will redirect to Facebook!
        $scope = $this->getParameter('scope_auth');
        if(!isset($scope)){
            $scope = [];
        }

        return $this->get('oauth2.registry')
            ->getClient('google_main') // key used in config.yml
            ->redirect($scope);
    }
1039847
public function getOAUTHInstance()
    {
        if (!is_object($this->oauth)) {
            $this->oauth = new PHPMailerOAuthGoogle(
                $this->oauthUserEmail,
                $this->oauthClientSecret,
                $this->oauthClientId,
                $this->oauthRefreshToken
            );
        }
        return $this->oauth;
    }
547162
public function token()
    {
        $response = $this->oauthServer->handleTokenRequest(Request::createFromGlobals());
        if (!$response->isSuccessful()) {
            return $this->response->sendError(
                ResponseCodes::AUTH_ERROR,
                $response->getStatusCode(),
                $response->getParameter('error_description')
            );
        } else {
            return $this->response->sendSuccess($response->getParameters());
        }
    }
670099
function oAuthRequest($url, $method, $parameters)
    {
        if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
            $url = "{$this->host}{$url}.{$this->format}";
        }
        $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
        $request->sign_request($this->sha1_method, $this->consumer, $this->token);
        switch ($method) {
            case 'GET':
                return $this->http($request->to_url(), 'GET');
            default:
                return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
        }
    }
923973
public function linkAccountCallback() {
    $sdk = $this->getSdk();

    if ($sdk instanceof RedirectResponse) {
      return $sdk;
    }

    $this->authManager->setSdk($sdk);

    // Get the OAuth token from Google.
    if (!$this->authManager->getAccessToken('link')) {
      drupal_set_message($this->t('@network login failed. Token is not valid.', [
        '@network' => $this->t('Google'),
      ]), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    // Get user's Google profile from Google API.
    if (!($profile = $this->authManager->getProfile()) || !($account_id = $profile->getId())) {
      drupal_set_message($this->t('@network login failed, could not load @network profile. Contact site administrator.', [
        '@network' => $this->t('Google'),
      ]), 'error');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    // Check whether any another user account already connected.
    $account = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties(['google_id' => $account_id]);
    $account = current($account);

    // Check whether another account was connected to this Google account.
    if ($account && (int) $account->id() !== (int) $this->currentUser()->id()) {
      drupal_set_message($this->t('Your @network account has already connected to another account on this site.', [
        '@network' => $this->t('Google'),
      ]), 'warning');
      return $this->redirect('entity.user.edit_form', [
        'user' => $this->currentUser()->id(),
      ]);
    }

    $account = User::load($this->currentUser()->id());
    $account->get('google_id')->setValue($account_id);
    $account->save();

    drupal_set_message($this->t('You are now able to log in with @network', [
      '@network' => $this->t('Google'),
    ]));
    return $this->redirect('entity.user.edit_form', [
      'user' => $account->id(),
    ]);
  }
857482
private function get_system_oauth_client() {
        if ($this->systemoauthclient === false) {
            try {
                $this->systemoauthclient = \core\oauth2\api::get_system_oauth_client($this->issuer);
            } catch (\moodle_exception $e) {
                $this->systemoauthclient = false;
            }
        }
        return $this->systemoauthclient;
    }