If we got a refresh token, use it to retrieve a good access token.
769845
private function refreshToken(\Google_Client $client): bool
    {
        $accessToken = $client->getAccessToken();
        $data = \json_decode($accessToken, true);

        try {
            if (isset($data['refresh_token'])) {
                $client->refreshToken($data['refresh_token']);

                return true;
            }
        } catch (\Google_Auth_Exception $e) {
        }

        return false;
    }
98979
public function getOauthRefreshToken($refresh_token)
    {
        $appid = $this->config->get('appid');
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appid}&grant_type=refresh_token&refresh_token={$refresh_token}";
        return $this->httpGetForJson($url);
    }
1248356
def _refresh_token(self):
        

        # use basic auth with API key and secret
        client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)

        # make request
        post_data = {"grant_type": "client_credentials"}
        response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
        self.last_response = response

        # raise exception if status code indicates an error
        if 400 <= response.status_code < 600:
            message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
                                                              "Client" if response.status_code < 500 else "Server",
                                                              self._get_trace_id(response),
                                                              "unable to get token")
            raise HTTPError(message, response=response)

        # set token property to the received token
        self.token = response.json()["access_token"]
989184
def refresh(self, access_token=None, **kwargs):
        
        if not self.token_lock.locked():
            with self.token_lock:
                if access_token == self.access_token or access_token is None:
                    if self.developer_token is not None:
                        r = self._httpclient.request(
                            method='POST',
                            url=self.developer_token_url,
                            path='/request_token',
                            headers={
                                'Authorization': 'Bearer {}'.format(
                                    self.developer_token
                                )
                            },
                            timeout=30,
                            raise_for_status=True
                        )

                    elif all(
                        [
                            self.client_id,
                            self.client_secret,
                            self.refresh_token
                        ]
                    ):
                        data = {
                            'client_id': self.client_id,
                            'client_secret': self.client_secret,
                            'refresh_token': self.refresh_token,
                            'grant_type': 'refresh_token'
                        }
                        r = self._httpclient.request(
                            method='POST',
                            url=self.token_url,
                            json=data,
                            path='/api/oauth2/RequestToken',
                            **kwargs
                        )
                    else:
                        raise PartialCredentialsError(
                            "Missing one or more required credentials"
                        )

                    if r:
                        if not r.ok:
                            raise PanCloudError(
                                '%s %s: %s' % (
                                r.status_code, r.reason, r.text)
                            )
                        try:
                            r_json = r.json()
                        except ValueError as e:
                            raise PanCloudError("Invalid JSON: %s" % e)
                        else:
                            if r.json().get(
                                'error_description'
                            ) or r.json().get(
                                'error'
                            ):
                                raise PanCloudError(r.text)
                            self.access_token = r_json.get(
                                'access_token', None
                            )
                            self.jwt_exp = self._decode_exp(
                                self.access_token_)
                            if r_json.get('refresh_token', None):
                                self.refresh_token = \
                                    r_json.get('refresh_token')
                            self.write_credentials()
                        return self.access_token_
94427
def _check_token(self):
        
        need_token = (self._token_info is None or
                      self.auth_handler.is_token_expired(self._token_info))
        if need_token:
            new_token = \
                self.auth_handler.refresh_access_token(
                    self._token_info['refresh_token'])
            # skip when refresh failed
            if new_token is None:
                return

            self._token_info = new_token
            self._auth_header = {"content-type": "application/json",
                                 "Authorization": "Bearer {}".format(
                                     self._token_info.get('access_token'))}
961818
public synchronized void refreshToken()
	{
		final String refreshToken = this.response.refresh_token;

		this.response = null;
		this.cachedInfo = null;

		final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_REFRESH_TOKEN,
		                                                null,
		                                                null,
		                                                clientId,
		                                                clientSecret,
		                                                refreshToken,
		                                                null,
		                                                null,
		                                                null);

		loadAuthResponse(responseStr);
	}
1179874
def get_access_token(self, request, callback=None):
        """"""
        callback = request.build_absolute_uri(callback or request.path)
        if not self.check_application_state(request):
            logger.error('Application state check failed.')
            return None
        if 'code' in request.GET:
            args = {
                'client_id': self.consumer_key,
                'redirect_uri': callback,
                'client_secret': self.consumer_secret,
                'code': request.GET['code'],
                'grant_type': 'authorization_code',
            }
        else:
            logger.error('No code returned by the provider')
            return None
        try:
            response = self.request('post', self.access_token_url, data=args)
            response.raise_for_status()
        except RequestException as e:
            logger.error('Unable to fetch access token: {0}'.format(e))
            return None
        else:
            return response.text
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
877852
public function refreshAccessToken(string $refresh_token): void
    {
        $data = [
            'appid' => $this->app_id,
            'grant_type' => 'refresh_token',
            'refresh_token' => $refresh_token,
        ];
        $url = self::REFRESH.http_build_query($data);
        $data = json_decode($this->curl->get($url));

        $access_token = $data->access_token;
        $expires_in = $data->expires_in;
        $refresh_token = $data->refresh_token;
        $open_id = $data->openid;
        $scope = $data->scope;
    }
1264129
def access_token
      @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"]
    end
719295
def refresh_token(self, refresh_token):
        

        response = requests.post('%saccess_token' % OAUTH_URL, {
                                 'refresh_token': refresh_token,
                                 'grant_type': 'refresh_token',
                                 'client_id': self.client_id,
                                 'client_secret': self.client_secret
                                 })
        resp = json.loads(response.content)

        if 'access_token' in resp:
            self.token = resp['access_token']

        return resp
332972
def auth_get_token(self, check_state=True):
		''
		res = self.auth_access_data_raw = yield self._auth_token_request()
		defer.returnValue(self._auth_token_process(res, check_state=check_state))
1050105
def get_token(self):
        
        if not self.authenticated:
            raise ValueError("Must authenticate() as a client first.")

        # If token has expired we'll need to refresh and get a new
        # client credential
        if self.is_expired_token(self.client):
            logging.info("client token expired, will need to refresh token")
            self.authenticate(self.client['id'], self.client['secret'],
                    use_cache=False)

        return self.client['access_token']
647791
def access_token(self) -> str:
        
        if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
            self.request_token()

        return self._token["access_token"]
1221812
def generate_access_token_from_refresh_token(request, client):
  
  refresh_token_value = request.POST.get('refresh_token')
  if not refresh_token_value:
    raise InvalidRequest('no "refresh_token" provided')

  try:
    existing_access_token = AccessToken.objects.get(
        refresh_token=refresh_token_value,
        client=client)
  except AccessToken.DoesNotExist:
    raise InvalidGrant('"{}" is not a valid "refresh_token"'.format(
      refresh_token_value))

  if existing_access_token.invalidated:
    refresh_token_used_after_invalidation.send(
        sender='djoauth2',
        access_token=existing_access_token,
        request=request)
    raise InvalidGrant('"{}" is not a valid "refresh_token"'.format(
      refresh_token_value))

  if not existing_access_token.refreshable:
    raise InvalidGrant('access token is not refreshable')

  # The specification (http://tools.ietf.org/html/rfc6749#section-6) describes
  # the scope parameter as follows:
  #
  #     scope
  #           OPTIONAL.  The scope of the access request as described by
  #           Section 3.3.  The requested scope MUST NOT include any
  #           scope not originally granted by the resource owner, and if
  #           omitted is treated as equal to the scope originally granted
  #           by the resource owner.
  #
  # This opens the possibility that a Client might successfully request a
  # subset of the existing scopes, but later in the same section comes the
  # following:
  #
  #      If a new refresh token is issued, the refresh token scope MUST be
  #      identical to that of the refresh token included by the client in the
  #      request.
  #
  # Confusingly, http://tools.ietf.org/html/rfc6749#section-1.5 includes the
  # following:
  #
  #     Refresh tokens are credentials used to obtain access tokens.  Refresh
  #     tokens are issued to the client by the authorization server and are
  #     used to obtain a new access token when the current access token becomes
  #     invalid or expires, or to obtain additional access tokens with
  #     identical or narrower scope (access tokens may have a shorter lifetime
  #     and fewer permissions than authorized by the resource owner).
  #
  # This last section explicitly allows tokens with narrower scope than
  # originally granted, which is in direct contradiction with the directive
  # that the scope must be equivalent to that granted earlier.
  #
  # Because the specification seems to contradict itself, I tend towards
  # observing the stricter directive (not allowing a subset of scope,) even
  # though to me there seems to be no reason to disallow that feature. That
  # said, I'm not sure why a client would ever ask for less scope than
  # originally granted.
  scope_objects = existing_access_token.scopes.all()
  new_scope_names = request.POST.get('scope', '')
  if new_scope_names:
    new_scope_names = new_scope_names.split(' ')
    if not existing_access_token.has_scope(*new_scope_names):
      raise InvalidScope('requested scopes exceed initial grant')

    scope_objects = []
    for scope_name in new_scope_names:
      try:
        scope_objects.append(Scope.objects.get(name=scope_name))
      except Scope.DoesNotExist:
        raise InvalidScope('"{}" is not a valid scope'.format(scope_name))

  requested_scope_string = request.POST.get('scope', '')
  if requested_scope_string:
    requested_scope_names = set(requested_scope_string.split(' '))
    if not requested_scope_names == existing_access_token.get_scope_names_set():
      raise InvalidScope('requested scopes do not match initial grant')


  # The new AccessToken is only refreshable if at the time of refresh the
  # server is configured to create refreshable tokens by default. It DOES NOT
  # inherit the existing token's 'refreshability' automatically. No behavior is
  # described in the specification; I believe this to be a sane decision.
  new_access_token = AccessToken.objects.create(
      user=existing_access_token.user,
      client=existing_access_token.client)
  new_access_token.authorization_code = existing_access_token.authorization_code
  new_access_token.scopes = scope_objects
  new_access_token.save()

  existing_access_token.invalidate()

  return new_access_token
401357
def use_refresh_token(self, refresh_token, scope=None):
        # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]]
        

        if refresh_token not in self.refresh_tokens:
            raise InvalidRefreshToken('{} unknown'.format(refresh_token))

        refresh_token_info = self.refresh_tokens[refresh_token]
        if 'exp' in refresh_token_info and refresh_token_info['exp'] < int(time.time()):
            raise InvalidRefreshToken('{} has expired'.format(refresh_token))

        authz_info = self.access_tokens[refresh_token_info['access_token']]

        if scope:
            if not requested_scope_is_allowed(scope, authz_info['granted_scope']):
                logger.debug('trying to refresh token with superset scope, requested_scope=%s, granted_scope=%s',
                             scope, authz_info['granted_scope'])
                raise InvalidScope('Requested scope includes non-granted value')
            scope = ' '.join(scope)
            logger.debug('refreshing token with new scope, old_scope=%s -> new_scope=%s', authz_info['scope'], scope)
        else:
            # OAuth 2.0: scope: "[...] if omitted is treated as equal to the scope originally granted by the resource owner"
            scope = authz_info['granted_scope']

        new_access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
                                                     authz_info['granted_scope'], scope)

        new_refresh_token = None
        if self.refresh_token_threshold \
                and 'exp' in refresh_token_info \
                and refresh_token_info['exp'] - int(time.time()) < self.refresh_token_threshold:
            # refresh token is close to expiry, issue a new one
            new_refresh_token = self.create_refresh_token(new_access_token.value)
        else:
            self.refresh_tokens[refresh_token]['access_token'] = new_access_token.value

        logger.debug('refreshed tokens, new_access_token=%s new_refresh_token=%s old_refresh_token=%s',
                     new_access_token, new_refresh_token, refresh_token)
        return new_access_token, new_refresh_token
529562
def refresh(params = {}, access_token_opts = {}, access_token_class = self.class)
      raise('A refresh_token is not available') unless refresh_token
      params[:grant_type] = 'refresh_token'
      params[:refresh_token] = refresh_token
      new_token = @client.get_token(params, access_token_opts, access_token_class)
      new_token.options = options
      new_token.refresh_token = refresh_token unless new_token.refresh_token
      new_token
    end