Use a refresh token to obtain a new access token
514523
def get_access_token(self, refresh_token):
        

        token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
            refresh_token=refresh_token,
            grant_type='refresh_token',
            client_id=self.client_id,
            client_secret=self.client_secret,
        )).json()

        if not token or token.get('error'):
            return

        return token
692784
public OAuthAccessToken refreshToken(RequestContext requestContext, OAuthAccessToken token) {
    OAuthAccessToken result = token;
    
    String[] scopes = token.getScopes();
    String tokenUrl = String.format("%s/realms/%s/protocol/openid-connect/token", getServerUrl(), getRealm());
    
    HttpPost httpPost = new HttpPost(tokenUrl);
    
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("client_id", getApiKey()));
      params.add(new BasicNameValuePair("client_secret", getApiSecret()));
      params.add(new BasicNameValuePair("grant_type", "refresh_token"));
      params.add(new BasicNameValuePair("refresh_token", token.getRefreshToken()));

      httpPost.setEntity(new UrlEncodedFormEntity(params));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        
        if (statusLine.getStatusCode() == 200) {
          HttpEntity entity = response.getEntity();
          
          ObjectMapper objectMapper = new ObjectMapper();
          try (InputStream stream = entity.getContent()) {
            RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(stream, RefreshTokenResponse.class);
            Date expiresAt = getExpiresAt(refreshTokenResponse.getExpiresIn());
            result = new OAuthAccessToken(token.getExternalId(), refreshTokenResponse.getAccessToken(), refreshTokenResponse.getRefreshToken(), expiresAt, scopes);
            AuthUtils.purgeOAuthAccessTokens(requestContext, getName());
            AuthUtils.storeOAuthAccessToken(requestContext, getName(), result);            
          }
          
          EntityUtils.consume(entity);
        } else {
          logger.log(Level.WARNING, String.format("Failed to refresh access token with message [%d]: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
      }
    } catch (IOException e) {
      logger.log(Level.WARNING, "Failed to refresh access token", e);
    }
    
    return result;
  }
1264129
def access_token
      @access_token ||= ShakeTheCounter::Authentication.renew_access_token(client_id: id, client_secret: secret, refresh_token: refresh_token)["access_token"]
    end
227705
def refresh_access_token(self, refresh_token, redirect_uri=None):
        '''
        
        '''
        redirect = redirect_uri or self._redirect_uri
        resp_text = _http('POST', 'https://graph.qq.com/oauth2.0/token',
                          refresh_token=refresh_token,
                          client_id=self._client_id, client_secret=self._client_secret,
                          redirect_uri=redirect, grant_type='refresh_token')
        return self._parse_access_token(resp_text)
1068927
def _exchange_refresh_tokens(self):
        ''
        if self.token_cache is not None and 'refresh' in self.token_cache:
            # Attempt to use the refresh token to get a new access token.
            refresh_form = {
                'grant_type': 'refresh_token',
                'refresh_token': self.token_cache['refresh'],
                'client_id': self.client_id,
                'client_secret': self.client_secret,
            }
            try:
                tokens = self._request_tokens_from_token_endpoint(refresh_form)
                tokens['refresh'] = self.token_cache['refresh']
                return tokens
            except OAuth2Exception:
                logging.exception(
                    'Encountered an exception during refresh token flow.')
        return None
62979
private function refreshToken()
    {

        // Make the post request for a new access_token
        $response = $this->httpRequest('post',
            $this->sso_base . '/token/?grant_type=refresh_token&refresh_token=' .
            $this->authentication->refresh_token, [
                'Authorization' => 'Basic ' . base64_encode(
                        $this->authentication->client_id . ':' . $this->authentication->secret),
            ]
        );

        // Get the current EsiAuth container
        $authentication = $this->getAuthentication();

        // Set the new authentication values from the request
        $authentication->access_token = $response->access_token;
        $authentication->refresh_token = $response->refresh_token;
        $authentication->token_expires = carbon('now')
            ->addSeconds($response->expires_in);

        // ... and update the container
        $this->setAuthentication($authentication);
    }
1141253
def refresh_token(self, headers=None, **kwargs):
        
        self._check_configuration("site", "token_url", "client_id",
                                  "client_secret")
        url = "%s%s" % (self.site, quote(self.token_url))
        data = {
            'client_id': self.client_id,
            'client_secret': self.client_secret,
        }
        data.update(kwargs)

        return self._make_request(url, data=data, headers=headers)
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
721471
def token_new():
    """"""
    form = TokenForm(request.form)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        t = Token.create_personal(
            form.data['name'], current_user.get_id(), scopes=form.scopes.data
        )
        db.session.commit()
        session['show_personal_access_token'] = True
        return redirect(url_for(".token_view", token_id=t.id))

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_new.html",
        form=form,
    )
264602
def save_token(self, access_token):
        
        self.access_tokens[access_token.token] = access_token

        unique_token_key = self._unique_token_key(access_token.client_id,
                                                  access_token.grant_type,
                                                  access_token.user_id)

        self.unique_token_identifier[unique_token_key] = access_token.token

        if access_token.refresh_token is not None:
            self.refresh_tokens[access_token.refresh_token] = access_token

        return True
732094
public function refreshAccessToken(OAuthToken $token)
    {
        $params = [
            'grant_type' => 'refresh_token'
        ];
        $params = array_merge($token->getParams(), $params);

        $request = $this->createRequest()
            ->setMethod('POST')
            ->setUrl($this->refreshTokenUrl)
            ->setData($params);

        $this->applyClientCredentialsToRequest($request);

        $response = $this->sendRequest($request);

        $token = $this->createToken(['params' => $response]);
        $this->setAccessToken($token);

        return $token;
    }
895039
function GetAccessToken(callback)
	{
		// do we have a refresh token? Or do we need to login from scratch?
		if (auth_obj.refresh_token)
		{
			// we have a refresh token!
			Log("Refreshing session...");

			if (!auth_obj.refresh_token)
			{
				if (callback) callback("No refresh token found!");
				return;
			}

			// request new access_token
			request.post(
				{
					url: urls.oauth,
					form: GetOAuthData({
						"grant_type": 		"refresh_token",
						"refresh_token": 	auth_obj.refresh_token
					})
				},
				function(err, response, body)
				{
					_ParseTokenResponse(err, body, callback);
				}
			);
		}
		else
		{
			// no refresh token, sign-in from scratch
			Log("Signing in with OAuth...");

			// make sure we have an authcode
			if (!auth_obj.auth_code)
			{
				if (callback) callback("No authcode available for OAuth!");
				return;
			}

			// request initial access_token
			request.post(
				{
					url: urls.oauth,
					form: GetOAuthData({
						"grant_type": 	"authorization_code",
						"code": 		auth_obj.auth_code
					})
				},
				function(err, response, body)
				{
					_ParseTokenResponse(err, body, callback);
				}
			);
		}
	}
78046
public function refreshToken($accessToken = null)
    {
        $accessToken = $accessToken ?: $this->accessToken;
        $this->accessToken = $this->provider->getAccessToken('refresh_token', [
            'refresh_token' => $accessToken->getRefreshToken()
        ]);
        return $this->accessToken;
    }
589178
def update_token(self):
        """"""
        logger.info('updating token')
        if None in self.credentials.values():
            raise RuntimeError("You must provide an username and a password")
        credentials = dict(auth=self.credentials)
        url = self.test_url if self.test else self.url
        response = requests.post(url + "auth",
                                 json=credentials)
        data = response.json()["response"]
        if "error_id" in data and data["error_id"] == "NOAUTH":
            raise BadCredentials()
        if "error_code" in data and data["error_code"] == "RATE_EXCEEDED":
            time.sleep(150)
            return
        if "error_code" in data or "error_id" in data:
            raise AppNexusException(response)
        self.token = data["token"]
        self.save_token()
        return self.token
404602
def refresh_token(self, arguments):
        

        new_access_token = None

        auth = ExistAuth(self.client_id, self.client_secret)
        resp = auth.refresh_token(self.access_token)
        if auth.token:
            new_access_token = auth.token['access_token']
            print('OAuth token refreshed: %s' % new_access_token)
            self.write_config(new_access_token)
        else:
            print('ERROR: We were unable to refresh the OAuth token | %s' % json.dumps(resp))
257235
public static function refreshToken(AccessToken $token, $params = null)
    {
        if ($token->expires_at > new \DateTime()) {
            return $token;
        }

        $requestor = new ApiRequestor(Sumup::$connectBase, true);
        $params = [
            'grant_type' => 'refresh_token',
            'client_id' => self::_getConnectParam('client_id', $params),
            'client_secret' => self::_getConnectParam('client_secret', $params),
            'refresh_token' => $token->refresh_token
        ];
        $response = $requestor->request('post', '/token', $params);

        if ($response->raw->getStatusCode() !== 200) {
            throw new Error\AuthenticationError('Token request error');
        }

        return new AccessToken($response);
    }
349577
def authorize_from_refresh_token(refresh_token)
      @access_token = oauth_client.get_token({
        client_id:     oauth_client.id,
        client_secret: oauth_client.secret,
        refresh_token: refresh_token,
        grant_type:    'refresh_token'
      })
    end