Request Client Credentials token
556141
public function requestClientCredentials($options = array()) {
        $options = array_merge(array(
            'scope' => '',
        ), $options);

        $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array(
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'grant_type' => 'client_credentials',
            'scope' => $options['scope'],
        ));
        $result = $res->getBody();

        $token = null;
        if ($result && $result = json_decode($result, true)) {
            if (!empty($result['error'])) {
                throw new Exception($result['error_description']);
            }

            if (!empty($result['access_token'])) {
                $this->accessToken = $token = $result['access_token'];
            }
        }

        if (empty($token)) {
            throw new InvalidTokenException('token not available.');
        }

        return $token;
    }
1237949
def get_token(self, payload):
        """"""

        auth = None
        if self.get_settings('OIDC_TOKEN_USE_BASIC_AUTH', False):
            # When Basic auth is defined, create the Auth Header and remove secret from payload.
            user = payload.get('client_id')
            pw = payload.get('client_secret')

            auth = HTTPBasicAuth(user, pw)
            del payload['client_secret']

        response = requests.post(
            self.OIDC_OP_TOKEN_ENDPOINT,
            data=payload,
            auth=auth,
            verify=self.get_settings('OIDC_VERIFY_SSL', True))
        response.raise_for_status()
        return response.json()
171735
def _request_access_token(self):
        
        payload = {'grant_type': 'authorization_code',
                   'code': code,
                   'redirect_uri': self.redirect_uri}

        headers = _make_authorization_headers(self.client_id,
                                              self.client_secret)

        response = requests.post(self.OAUTH_TOKEN_URL, data=payload,
                                 headers=headers,
                                 verify=LOGIN_VERIFY_SSL_CERT)

        if response.status_code is not 200:
            raise MercedesMeAuthError(response.reason)
        token_info = response.json()
        return token_info
1050017
function authenticate(req, cb) {
    request.post(
      'https://github.com/login/oauth/access_token',
      { form:
        { client_id: process.env.GHID,      // don't store credentials in opts
          client_secret: process.env.GHCS,  // get them straight from process.env
          code: req.query.code } },
      function(err, resp, body) {
        if (err) return cb(err);
        var result = qs.parse(body);
        getUser(req, result, function() {
          cb(null, result);
        });
      }
    );
  }
1257403
def _login(self, username, password, client_id, client_secret):
        """"""
        url = self.api_url + self.auth_token_url
        auth_string = '%s:%s' % (client_id, client_secret)
        authorization = base64.b64encode(auth_string.encode()).decode()
        headers = {
            'Authorization': "Basic " + authorization,
            'Content-Type': "application/x-www-form-urlencoded"
        }
        params = {
            'username': str(username),
            'password': str(password),
            # 'client_id': client_id,
            'grant_type': 'password',
            'response_type': 'token'
        }
        return self.session.post(url, params=params, headers=headers)
1318029
def obtain_access_token(self):
        
        if self.oauth_version != 2:
            raise TwythonError('This method can only be called when your \
                               OAuth version is 2.0.')

        data = {'grant_type': 'client_credentials'}
        basic_auth = HTTPBasicAuth(self.app_key, self.app_secret)
        try:
            response = self.client.post(self.request_token_url,
                                        data=data, auth=basic_auth)
            content = response.content.decode('utf-8')
            try:
                content = content.json()
            except AttributeError:
                content = json.loads(content)
                access_token = content['access_token']
        except (KeyError, ValueError, requests.exceptions.RequestException):
            raise TwythonAuthError('Unable to obtain OAuth 2 access token.')
        else:
            return access_token
712274
function getTokenFromHeader(request) {
  if (!request.headers || !request.headers.has('authorization')) {
    throw new UnauthorizedError('No authorization header present');
  }

  const parts = request.headers.get('authorization').split(" ");

  if (parts.length === 2) {
    const scheme = parts[0];
    const credentials = parts[1];

    if (/^Bearer$/i.test(scheme)) {
      return credentials;
    } else {
      throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
    }
  } else {
    throw new UnauthorizedError('Bad Authorization header format. Format is "Authorization: Bearer token"');
  }
}
1345657
def _obtain_token(self):
        """"""

        # don't renew token if hasn't expired yet
        if self.expiration and self.expiration > datetime.datetime.now():
            return

        resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "grant_type": "client_credentials"
        }).json()

        if "error" in resp:
            raise APIError("LibCal Auth Failed: {}, {}".format(resp["error"], resp.get("error_description")))

        self.expiration = datetime.datetime.now() + datetime.timedelta(seconds=resp["expires_in"])
        self.token = resp["access_token"]
        print(self.token)
901680
def fetch_credentials(auth_id, auth_token):
    """"""

    if not (auth_id and auth_token):
        try:
            auth_id = os.environ['PLIVO_AUTH_ID']
            auth_token = os.environ['PLIVO_AUTH_TOKEN']
        except KeyError:
            raise AuthenticationError('The Plivo Python SDK '
                                      'could not find your auth credentials.')

    if not (is_valid_mainaccount(auth_id) or is_valid_subaccount(auth_id)):
        raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id)

    return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token)
1275628
function(callback) {
        var self = this;

        var auth_post_data = querystring.stringify({
            'grant_type': 'client_credentials'
        });

        return new Promise(function(resolve, reject){
            self.client.methods.authentication_oauth(_.extend({}, self.requestOptions, {
                data: auth_post_data,
                headers: _.extend({}, self.requestOptions.headers, {
                    'Authorization': _getBasicAuthHash(self.config.clientId, self.config.clientApiKey),
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(auth_post_data)
                })
            }), function(data) {
                // Authorization succeeded
                if (data.token_type && data.access_token) {
                    _.extend(self.requestOptions.headers, {
                        'Authorization': data.token_type + ' ' + data.access_token
                    });
                    // Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms
                    self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 );
                    resolve(data);
                    if (_.isFunction(callback)) {
                        callback(data);
                    }
                } else {
                    reject(data);
                }
            }).on('error', function (err) { reject(err.message) });
        });
    }
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"]
247607
function client_auth_request(options) {
  const { client, } = options;
  return function(req, res, next) {
    if (!clientAuthToken[client.service_name]) {
      clientAuthToken[client.service_name] = new Buffer(client.client_token_id + ':' + client.client_secret).toString('base64');
    }
    req.controllerData = req.controllerData || {};
    req.controllerData.authorization_header = 'Basic ' + clientAuthToken[client.service_name];
    next();
  };
}
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'})
1128265
def get_user_token(login, password):
    """"""
    client = get_user_api()

    # Never use API key for the token endpoint
    config = cloudsmith_api.Configuration()
    set_api_key(config, None)

    with catch_raise_api_exception():
        data, _, headers = client.user_token_create_with_http_info(
            data={"email": login, "password": password}
        )

    ratelimits.maybe_rate_limit(client, headers)
    return data.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))
1027388
function verifyClientToken (req, res, next) {
  var header = req.headers['authorization']

  // missing header
  if (!header) {
    return next(new UnauthorizedError({
      realm: 'client',
      error: 'unauthorized_client',
      error_description: 'Missing authorization header',
      statusCode: 403
    }))

  // header found
  } else {
    var jwt = header.replace('Bearer ', '')
    var token = ClientToken.decode(jwt, settings.keys.sig.pub)

    // failed to decode
    if (!token || token instanceof Error) {
      next(new UnauthorizedError({
        realm: 'client',
        error: 'unauthorized_client',
        error_description: 'Invalid access token',
        statusCode: 403
      }))

    // decoded successfully
    } else {
      // validate token
      req.token = token
      next()
    }
  }
}
792979
def request_token(self):
        
        logging.debug("Getting request token from %s:%d",
                      self.server, self.port)
        token, secret = self._token("/oauth/requestToken")
        return "{}/oauth/authorize?oauth_token={}".format(self.host, token), \
            token, secret