Invalidate access tokens with a client/access token pair

        Returns:
            dict: Empty or error dict
492364
def invalidate(self):
        
        endpoint = '/invalidate'

        payload = {
            'accessToken': self.access_token,
            'clientToken': self.client_token,
        }
        self._ygg_req(endpoint, payload)
        self.client_token = ''
        self.access_token = ''
        self.available_profiles = []
        self.selected_profile = {}
        return True
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']
            }
        )
662544
def refresh_token(token, session=None):
    
    session = session or HTTP_SESSION
    refresh_data = dict(
        refresh_token=token.refresh_token,
        client_id=token.consumer_key,
        client_secret=token.consumer_secret,
        grant_type='refresh_token'
    )
    resp = session.post(REFRESH_TOKEN_URL, data=refresh_data)
    resp_json = resp.json()
    if 'error' in resp_json:
        message = resp_json['error']
        description = resp_json.get('error_description', '')
        if any(description):
            message = u'{}: {}'.format(message, description)
        raise OAuthTokenExpiredError(message)
    return OAuthToken(
        access_token=resp_json['access_token'],
        refresh_token=token.refresh_token,
        consumer_key=token.consumer_key,
        consumer_secret=token.consumer_secret
    )
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"]
1343034
def get_access_token(self, code, client_id, client_secret):
        ''' 
        
        '''
        headers = {
                'Content-Type' : 'application/json'
                }
        data = {
                'client_id' : client_id,
                'client_secret' : client_secret,
                'code' : code,
                }
        str_data = json.dumps(data)
        response = requests.request(method='POST', url=ACCESS_TOKEN_URL, headers=headers, data=str_data)
        status_code = response.status_code
        if status_code != 200:
            raise ValueError("{} -- {}".format(status_code, response.json()))
        return body['access_token']
1294581
def _convert_credentials(token_url, username=None, password=None, refresh_token=None):
    
    if username and password:
        data = {'grant_type': 'password', 'username': username, 'password': password}
    elif refresh_token:
        data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
    else:
        raise NotImplementedError()

    response = requests.post(token_url, data=data)
    if response.status_code == 401:
        raise Unauthorized('401 Client Error: Unauthorized')
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.utcnow() + timedelta(seconds=d['expires_in'])
        return Credentials(access_token=d['access_token'],
                           refresh_token=d['refresh_token'],
                           expiry=expiry)
    else:
        raise YamcsError('{} Server Error'.format(response.status_code))
154710
def get_access_token(self):
        
        if self.is_access_token_expired():

            if is_debug_enabled():
                debug('requesting new access_token')

            token = get_access_token(username=self.username,
                                     password=self.password,
                                     client_id=self.client_id,
                                     client_secret=self.client_secret,
                                     app_url=self.app_url)

            # lets make sure to refresh before we're halfway to expiring
            self.expires_at = time.time() + token['expires_in']/2
            self.access_token = token['access_token']

        return self.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
1320262
def revoke_token(access_token):
    
    response = requests.post(
        get_revoke_token_url(),
        data={
            'token': access_token,
            'client_id': settings.API_CLIENT_ID,
            'client_secret': settings.API_CLIENT_SECRET,
        },
        timeout=15
    )
    return response.status_code == 200
237263
def reset
      self.access_token       = DEFAULT_ACCESS_TOKEN
      self.access_token       = DEFAULT_INVESTOR_ID
      self.adapter            = DEFAULT_ADAPTER
      self.endpoint           = DEFAULT_ENDPOINT
      self.format             = DEFAULT_FORMAT
      self.user_agent         = DEFAULT_USER_AGENT
    end
628410
def _post_parse_request(self, request, client_id='', **kwargs):
        

        request = RefreshAccessTokenRequest(**request.to_dict())

        try:
            keyjar = self.endpoint_context.keyjar
        except AttributeError:
            keyjar = ""

        request.verify(keyjar=keyjar, opponent_id=client_id)

        if "client_id" not in request:  # Optional for refresh access token request
            request["client_id"] = client_id

        logger.debug("%s: %s" % (request.__class__.__name__, sanitize(request)))

        return request
814857
def access_token(self):

        '''  '''

        title = '%s.access_token' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # construct request kwargs
        request_kwargs = {
            'url': self.token_endpoint,
            'data': {
                'client_id': self.client_id,
                'client_secret': self.client_secret,
                'grant_type': 'client_credentials'
            }
        }

    # send request
        try:
            current_time = time()
            response = requests.post(**request_kwargs)
        except Exception:
            if self.requests_handler:
                request_kwargs['method'] = 'POST'
                request_object = requests.Request(**request_kwargs)
                return self.requests_handler(request_object)
            else:
                raise

        response_details = self.response_handler.handle(response)

        if response_details['json']:
            self._access_token = response_details['json']['access_token']
            expires_in = response_details['json']['expires_in']
            self.expires_at = current_time + expires_in
            
        return self._access_token
106550
def _GetAccessToken(self):
    
    d = {
        'assertion': self._GenerateAssertion(),
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    }
    try:
        body = parse.urlencode(d)
    except AttributeError:
        body = urllib.urlencode(d)
    req = urllib_request.Request(RpcHelper.TOKEN_ENDPOINT)
    req.add_header('Content-type', 'application/x-www-form-urlencoded')
    binary_body = body.encode('utf-8')
    raw_response = urllib_request.urlopen(req, binary_body)
    return simplejson.loads(raw_response.read())['access_token']
1046502
def mk_token(self, load):
        '''
        
        '''
        if not self.authenticate_eauth(load):
            return {}

        if self._allow_custom_expire(load):
            token_expire = load.pop('token_expire', self.opts['token_expire'])
        else:
            _ = load.pop('token_expire', None)
            token_expire = self.opts['token_expire']

        tdata = {'start': time.time(),
                 'expire': time.time() + token_expire,
                 'name': self.load_name(load),
                 'eauth': load['eauth']}

        if self.opts['keep_acl_in_token']:
            acl_ret = self.__get_acl(load)
            tdata['auth_list'] = acl_ret

        groups = self.get_groups(load)
        if groups:
            tdata['groups'] = groups

        return self.tokens["{0}.mk_token".format(self.opts['eauth_tokens'])](self.opts, tdata)
1325273
def revoke(self):
        
        if not self.refresh_token and not self.access_token:
            raise AttributeError('No access/refresh token are defined.')

        if self.refresh_token:
            data = {
                'token_type_hint': 'refresh_token',
                'token': self.refresh_token,
            }
        else:
            data = {
                'token_type_hint': 'access_token',
                'token': self.access_token,
            }

        request_data = self.__prepare_token_request(data, self.oauth_revoke)

        self._session.post(**request_data)
        self.access_token = None
        self.refresh_token = None
        self.token_expiry = None
1021457
def revoke_token(self, token, headers=None, **kwargs):
        
        self._check_configuration("site", "revoke_uri")
        url = "%s%s" % (self.site, quote(self.revoke_url))
        data = {'token': token}
        data.update(kwargs)

        return self._make_request(url, data=data, headers=headers)
1370302
def get_access_token(self, code=None, **params):
        
        if self._access_token is None:
            if code is None:
                raise ValueError(_('Invalid code.'))
            
            self.access_token_dict = self._get_access_token(code, **params)
            try:
                self._access_token = self.access_token_dict['access_token']
            except KeyError, e:
                raise OAuthError("Credentials could not be validated, the provider returned no access token.")
                
        return self._access_token