/*
Fetch a new access token.
322644
private synchronized void fetchAccessToken() throws ConnectionException, HTTPException {
        if (accessToken != null) {
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put(Constants.PARAM_CLIENT_ID, clientId);
        params.put(Constants.PARAM_CLIENT_SECRET, clientSecret);

        if (isUserAuthFlow()) {
            params.put(Constants.PARAM_GRANT_TYPE, Constants.PARAM_PASSWORD);
            params.put(Constants.PARAM_USERNAME, username);
            params.put(Constants.PARAM_PASSWORD, password);

        } else {
            params.put(Constants.PARAM_GRANT_TYPE, Constants.GRANT_TYPE_CLIENT_CREDENTIALS);
        }

        loadAccessToken(params);
    }
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;
	}
1087623
public function getAccessToken($force_new = false)
    {
        if ($this->guard->hasAccessToken()) {
            $access_token = $this->guard->getAccessToken();

            return $access_token;
        }

        return $this->generateAndStoreNewAccessToken();
    }
1005862
def access_token(self):
        """"""
        access_token = self.get_auth_bearer()
        if not access_token:
            access_token = self.query_kwargs.get('access_token', '')
            if not access_token:
                access_token = self.body_kwargs.get('access_token', '')

        return access_token
137563
private Identity fetch(final String token) throws IOException {
        final String uri = new Href(this.api).path("user")
            .with(PsGithub.ACCESS_TOKEN, token).toString();
        return PsGithub.parse(
            new JdkRequest(uri)
                .header("accept", "application/json")
                .fetch().as(RestResponse.class)
                .assertStatus(HttpURLConnection.HTTP_OK)
                .as(JsonResponse.class).json().readObject()
        );
    }
874748
function getToken (token, callback) {

    if (token != null &&
        token != '') {

        // Fetch token from database or cache

        if (token == 'h328hdkasjd3') {

            var record = { algorithm: 'hmac-sha-256',   // Required
                secret: '23hdkdho2893hdkjd',            // Required
                userId: 'johndoe'                       // Application-specific field
            };

            callback(record);
        }
        else {

            // Token not found

            callback({});
        }
    }
    else {

        // Invalid token request

        callback({});
    }
}
724806
def fetch_access_token(self, code):
        
        res = self._get(
            'sns/oauth2/access_token',
            params={
                'appid': self.app_id,
                'secret': self.secret,
                'code': code,
                'grant_type': 'authorization_code'
            }
        )
        self.access_token = res['access_token']
        self.open_id = res['openid']
        self.refresh_token = res['refresh_token']
        self.expires_in = res['expires_in']
        return res
107638
function fetchTokensData (tokenRegContract, tokenIndexes) {
  return (dispatch, getState) => {
    const { api, tokens } = getState();
    const allTokens = Object.values(tokens);

    const tokensIndexesMap = allTokens
      .reduce((map, token) => {
        map[token.index] = token;
        return map;
      }, {});

    const fetchedTokenIndexes = allTokens
      .filter((token) => token.fetched)
      .map((token) => token.index);

    const fullIndexes = [];
    const partialIndexes = [];

    tokenIndexes.forEach((tokenIndex) => {
      if (fetchedTokenIndexes.includes(tokenIndex)) {
        partialIndexes.push(tokenIndex);
      } else {
        fullIndexes.push(tokenIndex);
      }
    });

    log.debug('need to fully fetch', fullIndexes);
    log.debug('need to partially fetch', partialIndexes);

    const fullPromise = fetchTokensInfo(api, tokenRegContract, fullIndexes);
    const partialPromise = fetchTokensImages(api, tokenRegContract, partialIndexes)
      .then((imagesResult) => {
        return imagesResult.map((image, index) => {
          const tokenIndex = partialIndexes[index];
          const token = tokensIndexesMap[tokenIndex];

          return { ...token, image };
        });
      });

    return Promise.all([ fullPromise, partialPromise ])
      .then(([ fullResults, partialResults ]) => {
        log.debug('fetched', { fullResults, partialResults });

        return []
          .concat(fullResults, partialResults)
          .filter(({ address }) => !/0x0*$/.test(address))
          .reduce((tokens, token) => {
            const { id } = token;

            tokens[id] = token;
            return tokens;
          }, {});
      })
      .then((tokens) => {
        dispatch(setTokens(tokens));
      });
  };
}
1175934
private AccessToken getAccessToken() throws IOException {
    // synchronize attempts to refresh the accessToken
    synchronized (credentials) {
      if (needsRefresh(credentials.getAccessToken())) {
        credentialRefresher.refresh(credentials);
      }
    }
    return credentials.getAccessToken();
  }
362943
async function loadToken (url) {
  let tokens
  try {
    const data = await readFile(credentialsPath)
    tokens = JSON.parse(data)
  } catch (err) {}
  return tokens && tokens[url]
}
928713
public static FollowResult userGet(String access_token,String next_openid){
		HttpUriRequest httpUriRequest = RequestBuilder.get()
				.setUri(BASE_URI+"/cgi-bin/user/get")
				.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
				.addParameter("next_openid", next_openid==null?"":next_openid)
				.build();
		return LocalHttpClient.executeJsonResult(httpUriRequest,FollowResult.class);
	}
648267
def complete(self, GET):
        
        if 'error' in GET:
            raise OAuthError(
                _("Received error while obtaining access token from %s: %s") % (
                    self.access_token_url, GET['error']))
        return self.get_access_token(code=GET.get('code'))
342971
function refreshToken($accessToken, $sessionHandle) {
		$code = $this->request ( 'GET', $this->url ( 'AccessToken', '' ), array (
				'oauth_token' => $accessToken,
				'oauth_session_handle' => $sessionHandle 
		) );
		if ($this->response ['code'] == 200) {
			
			$response = $this->extract_params ( $this->response ['response'] );
			
			return $response;
		} else {
			$this->response ['helper'] = "TokenFatal";
			return $this->response;
		}
	}
36070
private function acquireAccessToken()
    {
        if (isset($this->accessToken) && $this->accessToken->getRefreshToken()) {
            return $this->provider->getAccessToken(new RefreshToken(), ['refresh_token' => $this->accessToken->getRefreshToken()]);
        }

        return $this->provider->getAccessToken($this->grant, $this->grantOptions);
    }
990171
public function acquireAccessToken()
  {
    $request = new Request(
        self::METADATA_AUTH_URL,
        'GET',
        array(
          'Metadata-Flavor' => 'Google'
        )
    );
    $request->disableGzip();
    $response = $this->client->getIo()->makeRequest($request);

    if ($response->getResponseHttpCode() == 200) {
      $this->setAccessToken($response->getResponseBody());
      $this->token['created'] = time();
      return $this->getAccessToken();
    } else {
      throw new Exception(
          sprintf(
              "Error fetching service account access token, message: '%s'",
              $response->getResponseBody()
          ),
          $response->getResponseHttpCode()
      );
    }
  }
608248
public static function fetch( $accessToken, $authCheck = true )
    {
        $tokenInfo = null;
        $session = ezcPersistentSessionInstance::get();
        $q = $session->createFindQuery( __CLASS__ );
        $e = $q->expr;

        $q->innerJoin( 'ezprest_clients', 'ezprest_token.client_id', 'ezprest_clients.client_id' );
        if ( $authCheck )
        {
            $q->innerJoin( 'ezprest_authorized_clients', $e->lAnd( $e->eq( 'ezprest_authorized_clients.rest_client_id', 'ezprest_clients.id' ),
                                                                   $e->eq( 'ezprest_authorized_clients.user_id', 'ezprest_token.user_id' ) ) );
        }

        $q->where( $q->expr->eq( 'ezprest_token.id', $q->bindValue( $accessToken ) ) );
        $tokenInfo = $session->find( $q, 'ezpRestToken' );
        if ( !empty( $tokenInfo ) )
        {
            $tokenInfo = array_shift( $tokenInfo );
        }
        else // Empty array. For consistency in result, cast it to null
        {
            $tokenInfo = null;
        }

        return $tokenInfo;
    }
7708
def _get_token(self, oauth_request, token_type='access'):
        """"""
        token_field = oauth_request.get_parameter('oauth_token')
        token = self.data_store.lookup_token(token_type, token_field)
        if not token:
            raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
        return token