Get the authorization header for a request, if needed.
Overrides this empty method in RestApiClient.

@param bool $forceRefresh - Should the token be refreshed, even if expiration timestamp hasn't passed?
@return array
@throws \Exception
559020
protected function getAuthorizationHeader($forceRefresh = false)
    {
        $token = $this->getAccessToken();

        // If we're using a token provided with the request, return it.
        if ($this->grant === 'provided_token') {
            return ['Authorization' => 'Bearer ' . $token->getToken()];
        }

        // Don't attempt to refresh token if there isn't a logged-in user.
        $user = $this->getFrameworkBridge()->getCurrentUser();
        if ($this->grant === 'authorization_code' && ! $user) {
            return [];
        }

        // If the token is expired, fetch a new one before making the request.
        if (! $token || ($token && $token->hasExpired()) || $forceRefresh) {
            $token = $this->refreshAccessToken($token);
        }

        return $this->getAuthorizationServer()->getHeaders($token);
    }
373521
public function refreshAuthority($inputs)
    {
        $result = $this->restCall('RefreshAuthority.json', $inputs);

        if ($result['Status'] == 100 || $result['Status'] == 101) {
            return ['Status' => 'success', 'refreshed' => true];
        } else {
            return ['Status' => 'error', 'error' => $result['Status']];
        }
    }
376270
public function getTokenByRefreshTokenGrant(AccessToken $oldToken)
    {
        try {
            $token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [
                'refresh_token' => $oldToken->getRefreshToken(),
                'scope' => $this->config[$this->grant]['scope'],
            ]);

            $this->getFrameworkBridge()->persistUserToken($token);

            return $token;
        } catch (IdentityProviderException $e) {
            $this->getFrameworkBridge()->requestUserCredentials();

            return null;
        }
    }
1107280
public function getAutoRefresh($index = '', array $options = [])
    {
        if (empty($index)) {
            if (empty($this->defaultIndex)) {
                throw new InvalidArgumentException('Unable to set auto refresh on index: no index specified');
            }

            $index = $this->defaultIndex;
        }

        $response = $this->query(
            $this->buildQueryArgs('index', 'getAutoRefresh', $index),
            [],
            $options
        );

        return $response['result'];
    }
1316526
public function refreshAccessToken(TokenInterface $token)
    {
        $refreshToken = $token->getRefreshToken();

        if (empty($refreshToken)) {
            throw new MissingRefreshTokenException();
        }

        $parameters = [
            'grant_type'    => 'refresh_token',
            'type'          => 'web_server',
            'client_id'     => $this->credentials->getConsumerId(),
            'client_secret' => $this->credentials->getConsumerSecret(),
            'refresh_token' => $refreshToken,
        ];

        $responseBody = $this->httpRequest(
            $this->getAccessTokenEndpoint(),
            $parameters,
            $this->getExtraOAuthHeaders()
        );
        $token = $this->parseAccessTokenResponse($responseBody);
        $this->storage->storeAccessToken($this->service(), $token);

        return $token;
    }
548571
public function getData($forceRefresh = false) {
		if ($forceRefresh || $this->_data === null) {
			if ($this->name === null) {
				throw new InvalidConfigException(get_class($this)." requires a name!");
			}
			$this->_data = $this->getConnection()->getSlave()->hgetall($this->name);
		}
		return $this->_data;
	}
852582
public function refreshAccessToken(AccessToken $token = null):AccessToken{

		if($token === null){
			$token = $this->storage->getAccessToken($this->serviceName);
		}

		$refreshToken = $token->refreshToken;

		if(empty($refreshToken)){

			if(!$this instanceof AccessTokenForRefresh){
				throw new ProviderException(sprintf('no refresh token available, token expired [%s]', date('Y-m-d h:i:s A', $token->expires)));
			}

			$refreshToken = $token->accessToken;
		}

		$body = [
			'client_id'     => $this->options->key,
			'client_secret' => $this->options->secret,
			'grant_type'    => 'refresh_token',
			'refresh_token' => $refreshToken,
			'type'          => 'web_server',
		];

		$request = $this->requestFactory
			->createRequest('POST', $this->refreshTokenURL ?? $this->accessTokenURL)
			->withHeader('Content-Type', 'application/x-www-form-urlencoded')
			->withHeader('Accept-Encoding', 'identity')
			->withBody($this->streamFactory->createStream(http_build_query($body, '', '&', PHP_QUERY_RFC1738)))
		;

		foreach($this->authHeaders as $header => $value){
			$request = $request->withAddedHeader($header, $value);
		}

		$newToken = $this->parseTokenResponse($this->http->sendRequest($request));

		if(empty($newToken->refreshToken)){
			$newToken->refreshToken = $refreshToken;
		}

		$this->storage->storeAccessToken($this->serviceName, $newToken);

		return $newToken;
	}
927282
public function getRefreshToken($tenantKey)
    {
        $tenantKey = $tenantKey == null ? $this->tenantKey : $tenantKey;
        if ($this->tenantTokens[$tenantKey] == null) {
            $this->tenantTokens[$tenantKey] = array();
        }
        return isset($this->tenantTokens[$tenantKey]['refreshToken'])
            ? $this->tenantTokens[$tenantKey]['refreshToken']
            : null;
    }
1118273
public function refreshUserAccessToken($refresh_token) {
		$data = $this->getData('/sns/oauth2/refresh_token', [
			'appid' => $this->app->appid,
			'grant_type' => 'refresh_token',
			'refresh_token' => $refresh_token,
		]);

		return $this->errcode == 0 ? $data : [];
	}
887290
def _request_token(self, force=False):
        
        if self.login_data is None:
            raise RuntimeError("Don't have a token to refresh")

        if not force:
            if not self._requires_refresh_token():
                # no need to refresh as token is valid
                return True

        headers = {
            "Accept": "application/json",
            'Authorization':
                'Bearer ' + self.login_data['token']['accessToken']
        }

        url = self.api_base_url + "account/RefreshToken"

        response = requests.get(url, headers=headers, timeout=10)

        if response.status_code != 200:
            return False

        refresh_data = response.json()

        if 'token' not in refresh_data:
            return False

        self.login_data['token']['accessToken'] = refresh_data['accessToken']
        self.login_data['token']['issuedOn'] = refresh_data['issuedOn']
        self.login_data['token']['expiresOn'] = refresh_data['expiresOn']

        return True
664810
protected function refreshExpiredCacheForContext($context = null, $forceRefresh = false)
    {
        $key = $this->getKey($context);
        if ($forceRefresh || $this->needRefresh($key)) {
            $this->logger->debug("Refreshing cache for $key ...");
            $this->cacheStorage->setItem($this->statusKeyFor($key), static::PENDING);
            $this->cacheStorage->setItem($key, serialize($this->getDataFromRealService($context)));
            $this->cacheStorage->setItem($this->statusKeyFor($key), static::COMPLETED);
            $this->cacheStorage->setItem($this->refreshedAtKeyFor($key), serialize($this->getDateTimeFactory()->now()));
            $this->logger->debug("Cache for $key has been refreshed !");
            return true;
        }
        return false;
    }
40889
private synchronized boolean refreshAuthToken(final AuthHandler handler,
                                                  final boolean forceRefresh) {

        if (handler == null) {
            return false;
        }

        AuthToken token = authToken.get();

        if (!forceRefresh && token != null && token.isValid()) {
            logger.fine("Auth token is already valid");
            return true;
        }

        try {
            handler.setForceRefresh(forceRefresh);
            token = handler.call();
            authToken.set(token);

            if (token != null) {
                if (token instanceof UserBearerAuthToken) {
                    final UserBearerAuthToken bt = (UserBearerAuthToken) token;
                    logger.info("Acquired auth token. Expires: "
                                + bt.getExpires() + " token="
                                + bt.getToken());
                } else if (token instanceof ProjectBearerAuthToken) {
                    ProjectBearerAuthToken pt = (ProjectBearerAuthToken) token;
                    logger.info("Acquired proj token. Expires: " + pt.getExpires() + " token="
                                + pt.getToken());
                } else {
                    logger.info("Acquired auth token. Token valid="
                                + token.isValid());
                }
            }
        } catch (ExecutionException e) {
            final Throwable cause = e.getCause();

            if (cause != null) {
                logger.warning("Authentication failed: " + cause.getMessage());
            } else {
                logger.warning("Authentication failed: " + e.getMessage());
            }
        } catch (Exception e) {
            logger.warning("Authentication failed: " + e.getMessage());
        } finally {
            handler.setForceRefresh(false);
        }
        return true;
    }
1177258
public function getCookie($forceRefresh = false)
    {
        $cacheKey = $this->cachePrefix . $this->stu_id;
        $cached = $this->getCache()->fetch($cacheKey);
        if ($forceRefresh || empty($cached)) {
            $jar = $this->login();
            //Cache the cookieJar 3000 s.
            $this->getCache()->save($cacheKey, serialize($jar), 3000);
            return $jar;
        }
        return unserialize($cached);
    }
122187
public function findAllToRefreshToken(bool $force = false)
    {
        $query = $this->newQuery();

        return $force ? $query->get() : $query->whereNull('token')->get();
    }
301448
public function getAuthorizerAccessToken($appId, $refreshToken)
    {
        $cacheKey = $this->getAuthorizerAccessTokenCacheKey($appId);
        $credential = $this->cache->get($cacheKey);
        if (!$credential || $credential['expireTime'] - time() < 60) {
            $ret = $this->authorizerToken($appId, $refreshToken);
            if ($ret['code'] !== 1) {
                return $ret;
            } else {
                $credential = [
                    'accessToken' => $ret['authorizer_access_token'],
                    'expireTime' => time() + $ret['expires_in'],
                    'refreshToken' => $ret['authorizer_refresh_token'],
                ];
                $this->cache->set($cacheKey, $credential);
            }
        }

        return $credential['accessToken'];
    }
257082
public function getData ($forceRefresh = false) {
        if ($forceRefresh || $this->_data === null) {
            $this->_data = $this->getConnection ()->getSlave ()->smembers ($this->name);
        }
        return $this->_data;
    }
604633
public function getToken($forceNew = false)
    {
        $tokenName = $this->getCacheKey();

        // see if token is in cache
        if (!$forceNew && $cachedToken = $this->cache->get($tokenName)) {
            $this->logger->debug('Obtained token from cache');
            $token = $this->createToken($cachedToken);
        }

        if (!isset($token) || !($token instanceof Token) || $token->isExpired()) {
            // cache the token and set it to expire 5 seconds before the
            // expiration date, to avoid any concurrence errors.
            $token = $this->requestToken();
            $this->cache->set($tokenName, json_encode($token), $token->getExpirationDate()->getTimestamp() - time() - 5);
        }

        // cache token properties
        $this->endpointUrl = $this->getEndpointUrlFromToken($token);
        $this->tokenId = $token->getId();

        return $token;
    }