Generate the authorization string to pass in via the http header.
Check if a token is linked to the connection object and use the client ID if there is not.
The method will also refresh the access token if it has expired.

@return string
977249
public function getAuthorizationToken()
    {
        $authorizationToken = "Client-ID {$this->provider->getClientId()}";

        if (! is_null($this->token)) {
            // Validate if the token object link to this class is expire
            // refresh it if it's the case
            if ($this->token->hasExpired()) {
                $this->refreshToken();
            }

            $authorizationToken = "Bearer {$this->token->getToken()}";
        }

        return $authorizationToken;
    }
441510
public function getOAuthToken()
    {
        if (!$this->isStateless()) {
            return \Cache::get('oauth.temp');
        } else {
            /** @var TemporaryCredentials $temp */
            $temp = unserialize(\Cache::get('oauth_temp'));

            return $temp->getIdentifier();
        }
    }
674398
public function getKey()
    {
        $key = '';

        if ($this->clientCredentials instanceof ClientCredentials) {
            $key .= rawurlencode($this->clientCredentials->getSecret());
        }

        // Keep the ampersand even if both keys are empty.
        $key .= '&';

        if ($this->serverIssuedCredentials instanceof ServerIssuedCredentials) {
            $key .= rawurlencode($this->serverIssuedCredentials->getSecret());
        }

        return $key;
    }
44855
public function getAuthorizationHeader($callbackUrl, $httpMethod = self::HTTP_GET)
    {
        $algorithm = 'HMAC-SHA1';
        if (false === ($signature = Base64::decode($this->secret))) {
            $this->addError(400, 'Invalid Consumer Secret');

            return false;
        }

        if (false === ($signature = Json::decode($signature))) {
            $this->addError(400, 'Invalid Consumer Secret');

            return false;
        }

        $algorithm = $signature->algorithm;

        $oauth = new \OAuth($this->key, $this->secret, $algorithm, OAUTH_AUTH_TYPE_AUTHORIZATION);

        $parameters = [
            'oauth_nonce'            => Generators\Nonce::generate($algorithm),
            'oauth_callback'         => $callbackUrl,
            'oauth_signature_method' => $algorithm,
            'oauth_timestamp'        => time(),
            'oauth_consumer_key'     => $this->key,
        ];

        $parameters[ 'oauth_signature' ] = $oauth->generateSignature($httpMethod, $callbackUrl, $parameters);
        $parameters[ 'oauth_version' ] = $this->version;

        $parts = [];
        foreach ($parameters as $key => $value) {
            $parts[] = $key . '="' . $value . '"';
        }

        return 'OAuth ' . implode(', ', $parts);
    }
168607
public String getAuthorizationHeader() {
    StringBuilder buf = new StringBuilder("OAuth");
    appendParameter(buf, "realm", realm);
    appendParameter(buf, "oauth_callback", callback);
    appendParameter(buf, "oauth_consumer_key", consumerKey);
    appendParameter(buf, "oauth_nonce", nonce);
    appendParameter(buf, "oauth_signature", signature);
    appendParameter(buf, "oauth_signature_method", signatureMethod);
    appendParameter(buf, "oauth_timestamp", timestamp);
    appendParameter(buf, "oauth_token", token);
    appendParameter(buf, "oauth_verifier", verifier);
    appendParameter(buf, "oauth_version", version);
    // hack: we have to remove the extra ',' at the end
    return buf.substring(0, buf.length() - 1);
  }
1260373
public function to_header() {/*{{{*/
    $out ='Authorization: OAuth realm=""';
    $total = array();
    foreach ($this->parameters as $k => $v) {
      if (substr($k, 0, 5) != "oauth") continue;
      if (is_array($v)) throw new OAuthException('Arrays not supported in headers');
      $out .= ',' . OAuthUtil::urlencode_rfc3986($k) . '="' . OAuthUtil::urlencode_rfc3986($v) . '"';
    }
    return $out;
  }
1295265
protected function _getAuthenticateChallengeHeader()
    {
        $wwwauth = 'Digest realm="' . $this->getRealm() . '", '
            /*
             * Domain directive is not meaningful in Proxy-Authenticate headers,
             * for which the protection space is always the entire proxy; if present
             * it should be ignored.
             */
            . ( ($this->getDomains()) ? 'domain="' . $this->domains . '", ' : '' )
            . 'nonce="' . $this->_generateNonce() . '", '
            /*
             * This can be treated as a session id. If this changes the browser
             * will deauthenticate the user.
             */
            . ( ($this->isUseOpaque()) ? 'opaque="' . $this->_generateOpaque() . '", ' : '' )
            /*
             * indicating that the previous request from the client was
             * rejected because the nonce value was stale. If stale is TRUE
             * (case-insensitive), the client may wish to simply retry the request
             * with a new encrypted response, without reprompting the user for a
             * new username and password. The server should only set stale to TRUE
             * if it receives a request for which the nonce is invalid but with a
             * valid digest for that nonce (indicating that the client knows the
             * correct username/password). If stale is FALSE, or anything other
             * than TRUE, or the stale directive is not present, the username
             * and/or password are invalid, and new values must be obtained.
             */
            . ( (isset($this->stale)) ? 'stale="true"' : '' )
            . 'algorithm="' . $this->defaultAlgorithm . '", '
            . 'qop="' . implode(',', $this->supportedQops) . '"';

        return $wwwauth;
    }
726002
public function getLoginUrl()
    {
        // required params
        $params = array(
            'client_id' => $this->getClientId(),
            'redirect_uri' => $this->getRedirectUri(),
        );
        // optional params
        if ($this->getScope()) {
            $params['scope'] = implode(',', $this->getScope());
        }
        if ($this->getResponceType()) {
            $params['response_type'] = $this->getResponceType();
        }
        if ($this->apiVersion) {
            $params['v'] = $this->apiVersion;
        }
        if ($this->state) {
            $params['state'] = $this->state;
        }

        return 'https://oauth.vk.com/authorize?' . http_build_query($params);
    }
525363
private static function connection()
    {
        if (!self::$connection) {
            self::$connection = new Connection();
            if (self::$client_id) {
                self::$connection->authenticateOauth(self::$client_id, self::$auth_token);
            } else {
                self::$connection->authenticateBasic(self::$username, self::$api_key);
            }
        }

        return self::$connection;
    }
36021
public function requestAccessToken()
    {
        $tokenUrl = $this->processUrl($this->server->getAccessTokenUrl());
        $accessToken = $this->instance->requestAccessToken($tokenUrl);
        $this->instance->setAccessToken($accessToken);

        return $accessToken;
    }
539258
public function to_string(): string
	{
		return 'oauth_token=' .
			Util::urlencode_rfc3986($this->key) .
			'&oauth_token_secret=' .
			Util::urlencode_rfc3986($this->secret);
	}
719419
public function refreshTokens()
    {
        $headers = array(
            'Content-Type' => 'application/x-www-form-urlencoded'
        );

        $headers = $this->injectUserAgent($headers);

        $res = $this->getHttpClient()->post($this->entrypoint . '/oauth/token', array(
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'refresh_token' => $this->getRefreshToken()
        ), array(
            'grant_type'=>'refresh_token'
        ), $headers);

        if(!$res || !empty($res['data']['error'])){
            throw new Exception($res['error'], Exception::API_ERROR);
        }

        $this->accessToken = $res['data']['access_token'];
        $this->refreshToken = $res['data']['refresh_token'];
        $this->expiresIn = (int)$res['data']['expires_in'];
        $this->scopes = explode(',', $res['data']['scope']);

        return $res['data'];
    }
247868
protected function createAuthorizationHeader(): string
    {
        $username = $this->getOption('api.username');
        $password = $this->getOption('api.password');

        // The API requires HTTP Basic Authentication, we can't proceed without credentials
        if ($username === null || $password === null) {
            throw new \InvalidArgumentException('Missing credentials for API authentication.');
        }

        return 'Basic ' . \base64_encode("$username:$password");
    }
358994
public function generateToken()
    {
        $adminUser = $this->auth->getUser();
        $refreshToken = $adminUser->getRefreshToken();

        if ($refreshToken) {
            $accessToken = $this->client->getAccessToken(
                $this->configFactory->getTokenUrl(),
                $this->buildUrlParams(
                    $this->helper->encryptor->decrypt($refreshToken)
                )
            );

            if (is_string($accessToken)) {
                return $accessToken;
            }
        }

        return false;
    }
766344
private function getAuthToken()
    {
        // Generate a new token if current is expired or empty
        if (!$this->token || new \DateTime() > $this->tokenExpireTime) {
            $this->requestToken();
        }

        return $this->token;
    }
93318
public static function token()
    {
        $token = null;

        if (self::has('server.HTTP_X_TOKEN')) {
            $token = self::get('server.HTTP_X_TOKEN', 'md5');
        }

        if (self::has('request._token')) {
            $token = self::get('request._token', 'md5');
        }

        return $token;
    }
354751
public function loginUrl()
    {
        $query = 'client_id=' . $this->app->getId() . '&redirect_uri=' . urlencode($this->callback) . '&response_type=code&state=' . $this->state;
        $query .= isset($this->scopes) ? '&scope=' . urlencode(str_replace(',', ' ', implode(',', $this->scopes))) : '';

        return sprintf('%s%s?%s', Constants::API_HOST, Constants::API_AUTH, $query);
    }