request token from FCM
557390
private String FCMGetFreshToken(final String senderID) {
        String token = null;
        try {
            if(senderID != null){
                getConfigLogger().verbose(getAccountId(), "FcmManager: Requesting a FCM token with Sender Id - "+senderID);
                token = FirebaseInstanceId.getInstance().getToken(senderID, FirebaseMessaging.INSTANCE_ID_SCOPE);
            }else {
                getConfigLogger().verbose(getAccountId(), "FcmManager: Requesting a FCM token");
                token = FirebaseInstanceId.getInstance().getToken();
            }
            getConfigLogger().info(getAccountId(),"FCM token: "+token);
        } catch (Throwable t) {
            getConfigLogger().verbose(getAccountId(), "FcmManager: Error requesting FCM token", t);
        }
        return token;
    }
72125
function logon() {
    var dfrd = Q.defer();
    var token = cache.get('token');

    function extractToken(xml) {
      var r = _parse(xml, dfrd);
      if (r) {
        return r.response.token[0];
      }
    }

    if (token) {
      dfrd.resolve({
        token: token,
        cached: true
      });
    }

    request(format(URLs.logon, PROTOCOL, conf.host, conf.username,
        conf.password),
      function(err, res, body) {
        var newToken;
        if (err) {
          dfrd.reject(err);
        } else {
          newToken = extractToken(body);
          if (!newToken) {
            dfrd.reject(MODULE_ERRORS.unknown);
          } else {
            cache.put('token', newToken);
            dfrd.resolve({
              token: newToken,
              cached: false
            });
          }
        }
      });
    return dfrd.promise;
  }
154107
def refresh_token(self, refresh_token, **kwargs):
        
        return self._token_request(grant_type='refresh_token',
                                   refresh_token=refresh_token, **kwargs)
794271
def _request(self, method, url, headers=None, params=None, **aio_kwargs):
        """"""
        access_token = params.pop(self.access_token_key, None)
        if access_token:
            headers['Authorization'] = "Bearer %s" % access_token
        return super(DiscordClient, self)._request(
            method, url, headers=headers, params=params, **aio_kwargs)
419021
function requestWithTokenCheck (defOptions, credentials, token, options, callback) {
  var returnedPromise;
  
  options.headers = options.headers || {};
  extend(true, options, defOptions);
  
  if (Date.now() - token.Timestamp > tokenUpdateTime) {
    returnedPromise = signIn(defOptions, credentials).then(function (data) {
      if (data[0].statusCode !== 200) {
        throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`);
      } else {
        token.AuthenticationToken = data[0].body.AuthenticationToken;
        token.Timestamp = Date.now();
        options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
        return request(options);
      }
    });
  } else {
    options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
    returnedPromise = request(options);
  }
  
  returnedPromise.nodeify(callback);
  return returnedPromise;
}
287153
def SecurityCheck(self, func, request, *args, **kwargs):
    """"""

    try:
      auth_header = request.headers.get("Authorization", "")
      if not auth_header.startswith(self.BEARER_PREFIX):
        raise ValueError("JWT token is missing.")

      token = auth_header[len(self.BEARER_PREFIX):]

      auth_domain = config.CONFIG["AdminUI.firebase_auth_domain"]
      project_id = auth_domain.split(".")[0]

      idinfo = id_token.verify_firebase_token(
          token, request, audience=project_id)

      if idinfo["iss"] != self.SECURE_TOKEN_PREFIX + project_id:
        raise ValueError("Wrong issuer.")

      request.user = idinfo["email"]
    except ValueError as e:
      # For a homepage, just do a pass-through, otherwise JS code responsible
      # for the Firebase auth won't ever get executed. This approach is safe,
      # because wsgiapp.HttpRequest object will raise on any attempt to
      # access uninitialized HttpRequest.user attribute.
      if request.path != "/":
        return self.AuthError("JWT token validation failed: %s" % e)

    return func(request, *args, **kwargs)
623719
def token_submit(self, token_id, json_data={}):
        
        uri = 'tokens/%s' % token_id
        post_body = json.dumps(json_data)

        resp, body = self.post(uri, post_body)
        self.expected_success(200, resp.status)
        body = json.loads(body)
        return rest_client.ResponseBody(resp, body)
83777
protected function requestToken()
    {
        $this->logger->debug('Requesting a new token');

        $data = [
            'auth' => [
                'passwordCredentials' => [
                    'password' => $this->tenant->getPassword(),
                    'username' => $this->tenant->getUsername(),
                ],
            ],
        ];

        if ($name = $this->tenant->getTenantName()) {
            $data['auth']['tenantName'] = $name;
        }

        try {
            $response = $this->client->request('POST', $this->tenant->getTokenUrl(), [
                RequestOptions::JSON => $data,
            ]);

            return $this->createToken($response->getBody()->getContents());
        } catch (RequestException $e) {
            $this->logger->error(sprintf('Error requesting token: %s', $e->getMessage()));

            throw new TokenException($e->getMessage(), $e->getCode(), $e);
        }
    }
884472
def request_access_token(self, params):
        
        return self.client().request(self.access_token_url, method="POST", body=urllib.urlencode(params), headers={'Content-Type':'application/x-www-form-urlencoded'})
877068
def create_request_token(self, request, credentials):
        
        token = {
            'oauth_token': self.token_generator(),
            'oauth_token_secret': self.token_generator(),
            'oauth_callback_confirmed': 'true'
        }
        token.update(credentials)
        self.request_validator.save_request_token(token, request)
        return urlencode(token.items())
613103
def _get_request_obj(csr):
    '''
    
    '''
    text = _text_or_file(csr)
    text = get_pem_entry(text, pem_type='CERTIFICATE REQUEST')
    return M2Crypto.X509.load_request_string(text)
151085
private void processFCM(AndroidVariant androidVariant, List<String> pushTargets, Message fcmMessage, ConfigurableFCMSender sender) throws IOException {


        // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed.
        if (pushTargets.get(0).startsWith(Constants.TOPIC_PREFIX)) {

            // perform the topic delivery

            for (String topic : pushTargets) {
                logger.info(String.format("Sent push notification to FCM topic: %s", topic));
                Result result = sender.sendNoRetry(fcmMessage, topic);

                logger.trace("Response from FCM topic request: {}", result);
            }
        } else {
            logger.info(String.format("Sent push notification to FCM Server for %d registrationIDs", pushTargets.size()));
            MulticastResult multicastResult = sender.sendNoRetry(fcmMessage, pushTargets);

            logger.trace("Response from FCM request: {}", multicastResult);

            // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion:
            cleanupInvalidRegistrationIDsForVariant(androidVariant.getVariantID(), multicastResult, pushTargets);
        }
    }
582567
def make_request_fn():
  """"""
  if FLAGS.cloud_mlengine_model_name:
    request_fn = serving_utils.make_cloud_mlengine_request_fn(
        credentials=GoogleCredentials.get_application_default(),
        model_name=FLAGS.cloud_mlengine_model_name,
        version=FLAGS.cloud_mlengine_model_version)
  else:

    request_fn = serving_utils.make_grpc_request_fn(
        servable_name=FLAGS.servable_name,
        server=FLAGS.server,
        timeout_secs=FLAGS.timeout_secs)
  return request_fn
1072025
def _cm_send_request(
	registration_ids, data, cloud_type="GCM", application_id=None,
	use_fcm_notifications=True, **kwargs
):
	

	payload = {"registration_ids": registration_ids} if registration_ids else {}

	data = data.copy()

	# If using FCM, optionnally autodiscovers notification related keys
	# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
	if cloud_type == "FCM" and use_fcm_notifications:
		notification_payload = {}
		if "message" in data:
			notification_payload["body"] = data.pop("message", None)

		for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
			value_from_extra = data.pop(key, None)
			if value_from_extra:
				notification_payload[key] = value_from_extra
			value_from_kwargs = kwargs.pop(key, None)
			if value_from_kwargs:
				notification_payload[key] = value_from_kwargs
		if notification_payload:
			payload["notification"] = notification_payload

	if data:
		payload["data"] = data

	# Attach any additional non falsy keyword args (targets, options)
	# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
	payload.update({
		k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
	})

	# Sort the keys for deterministic output (useful for tests)
	json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")

	# Sends requests and handles the response
	if cloud_type == "GCM":
		response = json.loads(_gcm_send(
			json_payload, "application/json", application_id=application_id
		))
	elif cloud_type == "FCM":
		response = json.loads(_fcm_send(
			json_payload, "application/json", application_id=application_id
		))
	else:
		raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
	return _cm_handle_response(registration_ids, response, cloud_type, application_id)
923315
private String GCMGetFreshToken(final String senderID) {
        getConfigLogger().verbose(getAccountId(), "GcmManager: Requesting a GCM token for Sender ID - " + senderID);
        String token = null;
        try {
            token = InstanceID.getInstance(context)
                    .getToken(senderID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            getConfigLogger().info(getAccountId(), "GCM token : " + token);
        } catch (Throwable t) {
            getConfigLogger().verbose(getAccountId(), "GcmManager: Error requesting GCM token", t);
        }
        return token;
    }
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
874748
function getToken (token, callback) {

    if (token != null &&
        token != '') {

        // Fetch token from database or cache

        if (token == 'h328hdkasjd3') {

            var record = { algorithm: 'hmac-sha-256',   // Required
                secret: '23hdkdho2893hdkjd',            // Required
                userId: 'johndoe'                       // Application-specific field
            };

            callback(record);
        }
        else {

            // Token not found

            callback({});
        }
    }
    else {

        // Invalid token request

        callback({});
    }
}