Refresh session's OAuth 2.0 credentials if they are stale.
182752
def refresh_oauth_credential(self):
        """"""
        if self.session.token_type == auth.SERVER_TOKEN_TYPE:
            return

        credential = self.session.oauth2credential
        if credential.is_stale():
            refresh_session = refresh_access_token(credential)
            self.session = refresh_session
1076842
def refresh(self):
        ""

        # Construct the credentials for the verification request
        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=self.oauth_token,
            resource_owner_secret=self.oauth_token_secret,
            rsa_key=self.rsa_key,
            signature_method=self._signature_method
        )

        # Make the verification request, getting back an access token
        headers = {'User-Agent': self.user_agent}
        params = {'oauth_session_handle': self.oauth_session_handle}
        response = requests.post(url=self.base_url + ACCESS_TOKEN_URL,
                params=params, headers=headers, auth=oauth)
        self._process_oauth_response(response)
1202283
def refresh_token!(refresh_token)
      old_token = OAuth2::AccessToken.new(oauth_client,'', refresh_token: refresh_token)
      self.access_token = old_token.refresh!
    end
1143710
public function refreshAccessToken()
    {
        $http = $this->getHTTPClient();
        $post_data = [
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret,
            'grant_type' => 'refresh_token',
            'refresh_token' => $this->refresh_token,
        ];

        // Refresh access token
        try {
            $response = $http->request('POST', 'oauth/access_token', [
                'form_params' => $post_data
            ]);

            $responseBody = $response->getBody();
            $responseArr = json_decode($responseBody, true);

            //Set new data into the config and update the current instance
            $this->setAccessToken($responseArr['access_token']);
            $this->setAccessTokenExpire($responseArr['expires_in']);
            $this->setRefreshToken($responseArr['refresh_token']);
        } catch (\Exception  $exception) {
            $this->handleException($exception);
        }
    }
527317
def validate_session(self, client, session):
        
        if session:
            if session._client is not client:
                raise InvalidOperation(
                    'Can only use session with the MongoClient that'
                    ' started it')
            if session._authset != self.authset:
                raise InvalidOperation(
                    'Cannot use session after authenticating with different'
                    ' credentials')
531576
public Credential refreshCredential(Credential credential) throws IOException {
    if (isCredentialRefreshable(credential)) {
      if (!callRefreshToken(credential)) {
        libLogger.warn("OAuth2 token could not be refreshed. "
            + "Add a refreshListener to the Credential to capture this failure.");
      }
    }
    return credential;
  }
577592
public boolean refreshSession (String sessionKey, int expireDays)
        throws PersistenceException
    {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, expireDays);
        Date expires = new Date(cal.getTime().getTime());

        // attempt to update an existing session row, returning true if we found and updated it
        return (update("update sessions set expires = '" + expires + "' " +
                       "where authcode = " + JDBCUtil.escape(sessionKey)) == 1);
    }
1220097
def request(self, uri, method='GET', body=None, headers=None,
                **kwargs):
        """"""

        _credential_refresh_attempt = kwargs.pop(
            '_credential_refresh_attempt', 0)

        # Make a copy of the headers. They will be modified by the credentials
        # and we want to pass the original headers if we recurse.
        request_headers = headers.copy() if headers is not None else {}

        self.credentials.before_request(
            self._request, method, uri, request_headers)

        # Check if the body is a file-like stream, and if so, save the body
        # stream position so that it can be restored in case of refresh.
        body_stream_position = None
        if all(getattr(body, stream_prop, None) for stream_prop in
               _STREAM_PROPERTIES):
            body_stream_position = body.tell()

        # Make the request.
        response, content = self.http.request(
            uri, method, body=body, headers=request_headers, **kwargs)

        # If the response indicated that the credentials needed to be
        # refreshed, then refresh the credentials and re-attempt the
        # request.
        # A stored token may expire between the time it is retrieved and
        # the time the request is made, so we may need to try twice.
        if (response.status in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts):

            _LOGGER.info(
                'Refreshing credentials due to a %s response. Attempt %s/%s.',
                response.status, _credential_refresh_attempt + 1,
                self._max_refresh_attempts)

            self.credentials.refresh(self._request)

            # Restore the body's stream position if needed.
            if body_stream_position is not None:
                body.seek(body_stream_position)

            # Recurse. Pass in the original headers, not our modified set.
            return self.request(
                uri, method, body=body, headers=headers,
                _credential_refresh_attempt=_credential_refresh_attempt + 1,
                **kwargs)

        return response, content
1179257
def cli(ctx, overwrite):
    """"""
    credentials_path = os.path.join(os.path.expanduser('~'), '.keep', '.credentials')
    if not os.path.exists(credentials_path):
        click.echo('You are not registered.')
        utils.register()
    else:
        utils.pull(ctx, overwrite)
269684
function (req, res, next) {
      if (req.query.return) {
        req.session.oauth2return = req.query.return;
      }
      next();
    }
672971
public void refreshCredentials() {
        if (this.credsProvider == null)
            return;

        try {
            AlibabaCloudCredentials creds = this.credsProvider.getCredentials();
            this.accessKeyID = creds.getAccessKeyId();
            this.accessKeySecret = creds.getAccessKeySecret();

            if (creds instanceof BasicSessionCredentials) {
                this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
1043191
private HeaderCacheElement syncRefresh(long timeout, TimeUnit timeUnit) {
    Span span = TRACER.spanBuilder("Bigtable.CredentialsRefresh").startSpan();
    try (Scope scope = TRACER.withSpan(span)) {
      return asyncRefresh().get(timeout, timeUnit);
    } catch (InterruptedException e) {
      LOG.warn("Interrupted while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("Authentication was interrupted.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      Thread.currentThread().interrupt();
      return new HeaderCacheElement(status);
    } catch (ExecutionException e) {
      LOG.warn("ExecutionException while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("ExecutionException during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } catch (TimeoutException e) {
      LOG.warn("TimeoutException while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("TimeoutException during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } catch (Exception e) {
      LOG.warn("Unexpected execption while trying to refresh google credentials.", e);
      Status status = Status.UNAUTHENTICATED
          .withDescription("Unexpected execption during Authentication.")
          .withCause(e);
      span.setStatus(StatusConverter.fromGrpcStatus(status));
      return new HeaderCacheElement(status);
    } finally {
      span.end();
    }
  }
178257
def refresh_session(self):
        

        if not self._refresh_token:
            if self._username and self._password:
                return self.login(self._username, self._password)

            return

        return self._authenticate(
            grant_type='refresh_token',
            refresh_token=self._refresh_token,
            client_id=self._client_id,
            client_secret=self._client_secret
        )
424744
def generate_session_token(refresh_token, verbose):
    

    platform = _get_platform(authenticated=False)
    session_token, expires_in = platform.generate_session_token(refresh_token)

    if verbose:
        click.echo("%s\n\n%s" % (session_token, _color('YELLOW', "Expires in %d seconds" % expires_in)))
    else:
        click.echo(session_token)
859699
def Refresh(self):
    
    with requests.Session() as session:
      session.proxies = self.proxy_config.proxies
      session.verify = not self.proxy_config.disable_certificate_validation
      session.cert = self.proxy_config.cafile

      self.creds.refresh(
          google.auth.transport.requests.Request(session=session))
1258372
async function refreshSession (ctx, session, originalHash, isNew) {

    // reject any session changes, and do not update session expiry
    if(ctx._sessionSave === false) {
      return debug('session save disabled')
    }

    //delete session
    if (!session) {
      if (!isNew) {
        debug('session set to null, destroy session: %s', ctx.sessionId)
        sessionIdStore.reset.call(ctx)
        return store.destroy(ctx.sessionId)
      }
      return debug('a new session and set to null, ignore destroy')
    }

    // force saving non-empty session
    if(ctx._sessionSave === true) {
      debug('session save forced')
      return saveNow(ctx, ctx.sessionId, session)
    }

    const newHash = hash(session)
    // if new session and not modified, just ignore
    if (!options.allowEmpty && isNew && newHash === EMPTY_SESSION_HASH) {
      return debug('new session and do not modified')
    }

    // rolling session will always reset cookie and session
    if (!options.rolling && newHash === originalHash) {
      return debug('session not modified')
    }

    debug('session modified')

    await saveNow(ctx, ctx.sessionId, session)

  }
479509
def authenticate(self):
        '''
        
        '''
        if "username" in self.options and "password" in self.options:
            self.login_oauth2(
                self.options["username"],
                self.options["password"],
                self.options.get('mfa_code'))
        elif "access_token" in self.options:
            if "refresh_token" in self.options:
                self.access_token = self.options["access_token"]
                self.refresh_token = self.options["refresh_token"]
                self.__set_account_info()
        else:
            self.authenticated = False
        return self.authenticated