duplicate the access token
331521
def dup_token(th):
    '''
    
    '''
    # TODO: is `duplicate_token` the same?
    sec_attr = win32security.SECURITY_ATTRIBUTES()
    sec_attr.bInheritHandle = True
    return win32security.DuplicateTokenEx(
       th,
       win32security.SecurityImpersonation,
       win32con.MAXIMUM_ALLOWED,
       win32security.TokenPrimary,
       sec_attr,
    )
1343019
public function updateAccessToken($access_token)
    {
        $this->getEventDispatcher()->addListener('request.before_send', function(Event $event) use($access_token){
            $request = $event['request'];
            $request->setHeader('Authorization ','Bearer '. $access_token);
        });
    }
513011
def renew_access_token(self):
        
        auth_params = {'REFRESH_TOKEN': self.refresh_token}
        self._add_secret_hash(auth_params, 'SECRET_HASH')
        refresh_response = self.client.initiate_auth(
            ClientId=self.client_id,
            AuthFlow='REFRESH_TOKEN',
            AuthParameters=auth_params,
        )

        self._set_attributes(
            refresh_response,
            {
                'access_token': refresh_response['AuthenticationResult']['AccessToken'],
                'id_token': refresh_response['AuthenticationResult']['IdToken'],
                'token_type': refresh_response['AuthenticationResult']['TokenType']
            }
        )
565342
public synchronized void refreshWithToken(String clientToken, String accessToken) throws AuthenticationException {
		authResult = authenticationService.refresh(Objects.requireNonNull(clientToken), Objects.requireNonNull(accessToken));
	}
428115
def try_replace_token(authenticate, **kwargs):
    

    try:
        return authenticate(**kwargs)
    except errors.BinstarError as err:
        if kwargs.get('fail_if_already_exists') and len(err.args) > 1 and err.args[1] == 400:
            logger.warning('It appears you are already logged in from host %s' % socket.gethostname())
            logger.warning('Logging in again will remove the previous token. (This could cause troubles with virtual '
                           'machines with the same hostname)')
            logger.warning('Otherwise you can login again and specify a different hostname with "--hostname"')

            if bool_input("Would you like to continue"):
                kwargs['fail_if_already_exists'] = False
                return authenticate(**kwargs)

        raise
147825
function (done) {
      // the token is random
      if (token.indexOf('.') === -1) {
        AccessToken.get(token, function (err, instance) {
          if (err) {
            return done(err)
          }

          if (!instance) {
            return done(new UnauthorizedError({
              realm: 'user',
              error: 'invalid_request',
              error_description: 'Unknown access token',
              statusCode: 401
            }))
          }

          done(null, {
            jti: instance.at,
            iss: instance.iss,
            sub: instance.uid,
            aud: instance.cid,
            iat: instance.created,
            exp: instance.created + instance.ei,
            scope: instance.scope
          })
        })

      // the token is not random
      } else {
        done()
      }
    }
80929
function copyAsUser($from, $to)
    {
        copy($from, $to);

        $this->chown($to, user());
    }
940134
def save_token(self, access_token):
        
        self.write(access_token.token, access_token.__dict__)

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

        if access_token.refresh_token is not None:
            self.write(access_token.refresh_token, access_token.__dict__)
703044
def refresh_token(self):
        
        self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
        self.access_token = self.token.get("access_token")
932898
def auth_as(self, user):
        """"""
        old_user = self._user
        self.auth(user)
        try:
            yield
        finally:
            self.auth(old_user)
912372
function getAccessToken(authCode, callback) {
	debug('Getting access token');
	var responseJSON;
	if (refreshToken.length > 0) {
		request.post(psnURL.oauth, {form:{ // Refreshing the token with refresh_token to avoid login again
				 'grant_type'	: 'refresh_token'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'refresh_token': refreshToken
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						debug('access_token obtained by using refresh_token: ' + accessToken)
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + responseJSON)
					}
				}
				else {
					debug('ERROR: ' + error)
				}
		})
	}
	else {
		debug('Login for the first time');
		request.post(psnURL.oauth, {form:{ // Firts time login
				 'grant_type'	: 'authorization_code'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'code' 		: authCode
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						clearInterval(refreshInterval);
						refreshInterval = setInterval(function() {
							getAccessToken('', function() {
								debug('access_token refreshed after 59 minutes')
							})
						}, (responseJSON.expires_in - 60) * 1000) // 59 minutes
						debug('access_token/refresh_token obtained: ' + body);
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + JSON.stringify(responseJSON))
					}
				}
				else {
					debug('ERROR: ' + JSON.stringify(error))
				}
		})	
	}
}
503047
private function refreshAccessToken() {
        // Setup the params
        $params = [
            'client_id'     => $this->clientID,
            'client_secret' => $this->secret,
            'grant_type'    => 'refresh_token',
            'refresh_token' => $this->refreshToken
        ];

        // Parse the cURL result
        $this->parseAccessToken(CURL::post($this->url, $params));
    }
786074
def change_authentication(self, client_id=None, client_secret=None,
                              access_token=None, refresh_token=None):
        """"""
        # TODO: Add error checking so you cannot change client_id and retain
        # access_token. Because that doesn't make sense.
        self.client_id = client_id or self.client_id
        self.client_secret = client_secret or self.client_secret
        self.access_token = access_token or self.access_token
        self.refresh_token = refresh_token or self.refresh_token
531614
def duplicate(self, request, *args, **kwargs):
        """"""
        if not request.user.is_authenticated:
            raise exceptions.NotFound

        ids = self.get_ids(request.data)
        queryset = get_objects_for_user(request.user, 'view_collection', Collection.objects.filter(id__in=ids))
        actual_ids = queryset.values_list('id', flat=True)
        missing_ids = list(set(ids) - set(actual_ids))
        if missing_ids:
            raise exceptions.ParseError(
                "Collections with the following ids not found: {}".format(', '.join(map(str, missing_ids)))
            )

        duplicated = queryset.duplicate(contributor=request.user)

        serializer = self.get_serializer(duplicated, many=True)
        return Response(serializer.data)
255361
final protected function refreshToken()
    {
        $oldAccessToken = $this->accessToken;

        if ($this->accessToken->getRefreshToken()) {
            $this->accessToken = $this->provider->getAccessToken(self::GRANT_REFRESH_TOKEN, [
                'refresh_token' => $this->accessToken->getRefreshToken(),
            ]);
        } else {
            // request a completely new access token
            $this->accessToken = $this->requestAccessToken();
        }

        if ($this->refreshTokenCallback) {
            call_user_func($this->refreshTokenCallback, $this->accessToken, $oldAccessToken);
        }
    }
516920
def create_refresh_token(self, access_token_value):
        # type: (str) -> str
        
        if access_token_value not in self.access_tokens:
            raise InvalidAccessToken('{} unknown'.format(access_token_value))

        if not self.refresh_token_lifetime:
            logger.debug('no refresh token issued for for access_token=%s', access_token_value)
            return None

        refresh_token = rand_str()
        authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}
        self.refresh_tokens[refresh_token] = authz_info

        logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],
                     access_token_value)
        return refresh_token
1355445
def duplicate(self):
        '''
        
        '''
        return self.__class__(amount=self.amount, date=self.date,
                              method=self.method, ref=self.ref)