Persist the token with a token type specific method.

        Currently, only save_bearer_token is supported.

        :param token: A (Bearer) token dict.
        :param request: OAuthlib request.
        :type request: oauthlib.common.Request
485584
def save_token(self, token, request, *args, **kwargs):
        
        return self.save_bearer_token(token, request, *args, **kwargs)
117172
private void saveTokenFromResponse(Response response) {
        try {
            JSONObject responseJSON = ((ResponseImpl)response).getResponseJSON();

            String accessToken = responseJSON.getString("access_token");
            String idToken = responseJSON.getString("id_token");

            //save the tokens
            preferences.accessToken.set(accessToken);
            preferences.idToken.set(idToken);

            //save the user identity separately
            String[] idTokenData = idToken.split("\\.");
            byte[] decodedIdTokenData = Base64.decode(idTokenData[1], Base64.DEFAULT);
            String decodedIdTokenString = new String(decodedIdTokenData);
            JSONObject idTokenJSON = new JSONObject(decodedIdTokenString);

            if (idTokenJSON.has("imf.user")) {
                preferences.userIdentity.set(idTokenJSON.getJSONObject("imf.user"));
            }

            logger.debug("token successfully saved");
        } catch (Exception e) {
            throw new RuntimeException("Failed to save token from response", e);
        }
    }
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
349093
def post(self, request, data=None):
        
        headers = {"Authorization": "Bearer " + self.token }
        logging.debug(json.dumps(data, indent=4))
        p = requests.post(self.url + request, headers=headers, data=json.dumps(data))
        return json.loads(p.text)
1359913
def core_oauth_token_create(self, data, **kwargs):
        ""
        api_path = "/oauth/tokens"
        return self.call(api_path, method="POST", data=data, **kwargs)
1314861
def callback(self, request, **kwargs):
        
        access_token = request.session['oauth_token'] + "#TH#"
        access_token += str(request.session['oauth_id'])
        kwargs = {'access_token': access_token}
        return super(ServiceGithub, self).callback(request, **kwargs)
587481
def request(self, method, url, **kwargs):
        ""
        user_token = kwargs.pop('token', self.token)
        token, _ = self.parse_raw_token(user_token)
        if token is not None:
            params = kwargs.get('params', {})
            params['access_token'] = token
            kwargs['params'] = params
        return super(OAuth2Client, self).request(method, url, **kwargs)
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
1104833
def _make_request(
            self, api_resource, method='GET', params=None, **kwargs):
        
        if kwargs.get('json'):
            headers = {
                'Authorization': 'Bearer {}'.format(self._token),
                'Content-Type': 'application/json'
            }
        else:
            headers = {
                'Authorization': 'Bearer {}'.format(self._token)
            }

        response = requests.request(
            method=method,
            url='{0}{1}'.format(self.BASE_API_URL, api_resource),
            headers=headers,
            params=params,
            **kwargs
        )

        if response.status_code >= 400:
            error_response = response.json()

            raise(ToshlException(
                status_code=response.status_code,
                error_id=error_response['error_id'],
                error_description=error_response['description'],
                extra_info=error_response.get('fields')))

        return response
647173
def request(self, method, url, **kwargs):
        

        if "data" in kwargs:
            kwargs["data"] = json.dumps(kwargs["data"])

        kwargs["headers"] = {
            'Content-Type': 'application/json',
            'Authorization': 'token %s' % self.__token__,
        }
        req = make_request(
            method,
            url,
            **kwargs
        )
        self.logger.debug(
            "Request::{}::{}".format(method, url),
            extra={
                "request": kwargs,
                "response": {"headers": req.headers, "code": req.status_code, "data": req.content}
            }
        )
        return req
779797
def authenticate_token(self, load):
        '''
        
        '''
        token = self.get_tok(load['token'])

        # Bail if the token is empty or if the eauth type specified is not allowed
        if not token or token['eauth'] not in self.opts['external_auth']:
            log.warning('Authentication failure of type "token" occurred.')
            return False

        return token
130356
def create_token_response(self, uri, http_method='GET', body=None,
                              headers=None, credentials=None):
        """"""
        django_request = headers.pop("Django-request-object", None)
        request = Request(
            uri, http_method=http_method, body=body, headers=headers)
        request.scopes = None
        request.extra_credentials = credentials
        request.django_request = django_request
        grant_type_handler = self.grant_types.get(request.grant_type,
                                                  self.default_grant_type_handler)
        log.debug('Dispatching grant_type %s request to %r.',
                  request.grant_type, grant_type_handler)
        return grant_type_handler.create_token_response(
            request, self.default_token_type)
1360868
def token_protected_endpoint(function):
  
  @wraps(function)
  def decorated(*args, **kwargs):
    auth_token = request.form.get('auth_token')
    if not auth_token:
      return json.dumps({
        'status': 'fail',
        'reason': 'You must provide an auth_token',
      })

    data = dict(request.form)
    del data['auth_token']
    correct_token = create_token(current_app.config['SECRET_KEY'], data)

    if _compare_digest(auth_token, correct_token):
      return function(*args, **kwargs)

    else:
      return json.dumps({
        'status': 'fail',
        'reason': 'Incorrect auth_token',
      })

  return decorated
644990
def on_post(self, req, resp):
        

        token = req.get_param('token')
        token_type_hint = req.get_param('token_type_hint')

        # errors or not, disable client caching along the way
        # per the spec
        resp.disable_caching()

        if not token:
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'invalid_request',
                'error_description': 'A token parameter is required during '
                                     'revocation according to RFC 7009.',
                'error_uri': 'tools.ietf.org/html/rfc7009#section-2.1',
            })
        elif token_type_hint == 'refresh_token':
            resp.status = falcon.HTTP_400
            resp.serialize({
                'error': 'unsupported_token_type',
                'error_description': 'Currently only access_token types can '
                                     'be revoked, NOT refresh_token types.',
                'error_uri': 'tools.ietf.org/html/rfc7009#section-2.2.1',
            })
        else:
            # ignore return code per section 2.2
            self.revoke_token(token)
            resp.status = falcon.HTTP_200
3063
def fetch_request_token(self, oauth_request):
        
        try:
            # Get the request token for authorization.
            token = self._get_token(oauth_request, 'request')
        except Error:
            # No token required for the initial token request.
            version = self._get_version(oauth_request)
            consumer = self._get_consumer(oauth_request)
            try:
                callback = self.get_callback(oauth_request)
            except Error:
                callback = None # 1.0, no callback specified.
            self._check_signature(oauth_request, consumer, None)
            # Fetch a new token.
            token = self.data_store.fetch_request_token(consumer, callback)
        return token
60597
def get_token(self, client_id, target, api_type, grant_type,
                  id_token=None, refresh_token=None, scope='openid'):

        

        if id_token and refresh_token:
            raise ValueError('Only one of id_token or refresh_token '
                             'can be None')

        data = {
            'client_id': client_id,
            'grant_type': grant_type,
            'target': target,
            'scope': scope,
            'api_type': api_type,
        }

        if id_token:
            data.update({'id_token': id_token})
        elif refresh_token:
            data.update({'refresh_token': refresh_token})
        else:
            raise ValueError('Either id_token or refresh_token must '
                             'have a value')

        return self.post(
            'https://{}/delegation'.format(self.domain),
            headers={'Content-Type': 'application/json'},
            data=data
        )
1145188
def request(self, method, path, params=None, headers=None, body=None):
        
        if not headers:
            headers = {}
        if not params:
            params = {}

        headers["Accept"] = "application/json"
        headers["Accept-Version"] = "^1.15.0"
        if self.auth_token:
            headers["Authorization"] = "Bearer {0}".format(self.auth_token)

        path = self.url + path
        params = self.flatten_params(params)
        response = requests.request(method, path, params=params, headers=headers, json=body)

        result = response.text
        try:
            result = response.json()
        except Exception:
            pass

        if response.status_code >= 400:
            raise LosantError(response.status_code, result)

        return result