How to use the oauth2client.client.GoogleCredentials.get_application_default function in oauth2client

To help you get started, we’ve selected a few oauth2client examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / citest / citest / gcp_testing / gcp_agent.py View on Github external
api = default_api
      version = version or default_version

    if version is None:
      version = GcpAgent.determine_current_version(api)

    http = httplib2.Http()
    http = apiclient.http.set_user_agent(
        http, 'citest/{version}'.format(version=citest.__version__))
    credentials = None
    if credentials_path is not None:
      logger.info('Authenticating %s %s', api, version)
      credentials = ServiceAccountCredentials.from_json_keyfile_name(
          credentials_path, scopes=scopes)
    else:
      credentials = GoogleCredentials.get_application_default()
      if scopes and credentials.create_scoped_required():
        credentials = credentials.create_scoped(scopes)

    http = credentials.authorize(http)
    logger.info('Constructing %s service...', api)
    return apiclient.discovery.build(api, version, http=http)
github nccgroup / G-Scout / core / config.py View on Github external
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage

CLIENT_ID = '206629590950-6o7fig55aupliolgt6o10obpnagdf4pd.apps.googleusercontent.com'
CLIENT_SECRET = 'qgRgh8NA4Y8Qlqn7r7ulrKXV'  # not actually a secret
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
                           client_secret=CLIENT_SECRET,
                           scope='https://www.googleapis.com/auth/cloud-platform')

storage = Storage('../creds.data')
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args(args=[])

if os.path.isfile('keyfile.json'):
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.getcwd() + "/keyfile.json"
    creds = GoogleCredentials.get_application_default()
else:
    creds = tools.run_flow(flow, storage, flags)

storage.put(creds)
github IntelligentTrading / core / bigtable / read_data.py View on Github external
""" Input new data into BigTable

    Args:
        project_id: Id of GCP Project
        instance_id: BigTable instance id
        table_id: just Table id
        column_family: column family name
        column: column name
        start_row_key: start name of row key (optional)
        end_row_key: end name of row key (optional)

    Returns:
        Dictionary with row keys and values or None
    """
    try:
        GoogleCredentials.get_application_default()
        client = bigtable.Client(project=project_id, admin=True)
        instance = client.instance(instance_id)

        table = instance.table(table_id)

        partial_rows = table.read_rows(start_key=start_row_key,
                                       end_key=end_row_key)
        partial_rows.consume_all()

        values = {}

        for row_key, row in partial_rows.rows.items():
            key = row_key.decode('utf-8')
            cell = row.cells[column_family][column.encode('UTF-8')][0]
            value = cell.value.decode('utf-8')
            values[key] = value
github elasticluster / elasticluster / elasticluster / providers / gce.py View on Github external
# access through the web interface once.
            storage_path = os.path.join(self._storage_path,
                                        self._client_id + '.oauth.dat')
            storage = Storage(storage_path)

            credentials = storage.get()
            if credentials is not None and not credentials.invalid:
                return credentials
            else:
                log.info("Determined that provided credentials are not valid.")

        try:
            # Next, check to see if there is a set of application
            # default credentials to use.
            log.info("Attempting to use Google Application Default Credentials.")
            return GoogleCredentials.get_application_default()
        except ApplicationDefaultCredentialsError:
            log.info("Failed to use Google Application Default Credentials, falling back to config.")
            log.debug("(Original traceback follows.)", exc_info=True)

        try:
            # Finally, try to start a browser to have the user authenticate with Google
            args = argparser.parse_args([])
            args.noauth_local_webserver = self._noauth_local_webserver
            return run_flow(flow, storage, flags=args)
        except Exception as err:
            log.error("Could not run authentication flow: %s", err)
            log.debug("(Original traceback follows.)", exc_info=True)
        raise CredentialsError("No method to obtain GCE credentials was successful!  Either "
                               "set up Application Default Credentials using gcloud, or "
github lyft / cartography / cartography / intel / gcp / __init__.py View on Github external
"""
    Starts the GCP ingestion process by initializing Google Application Default Credentials, creating the necessary
    resource objects, listing all GCP organizations and projects available to the GCP identity, and supplying that
    context to all intel modules.
    :param neo4j_session: The Neo4j session
    :param config: A `cartography.config` object
    :return: Nothing
    """
    common_job_parameters = {
        "UPDATE_TAG": config.update_tag,
    }
    try:
        # Explicitly use Application Default Credentials.
        # See https://oauth2client.readthedocs.io/en/latest/source/
        #             oauth2client.client.html#oauth2client.client.OAuth2Credentials
        credentials = GoogleCredentials.get_application_default()
    except ApplicationDefaultCredentialsError as e:
        logger.debug("Error occurred calling GoogleCredentials.get_application_default().", exc_info=True)
        logger.error(
            (
                "Unable to initialize Google Compute Platform creds. If you don't have GCP data or don't want to load "
                "GCP data then you can ignore this message. Otherwise, the error code is: %s "
                "Make sure your GCP credentials are configured correctly, your credentials file (if any) is valid, and "
                "that the identity you are authenticating to has the securityReviewer role attached."
            ),
            e,
        )
        return
    resources = _initialize_resources(credentials)

    # If we don't have perms to pull Orgs or Folders from GCP, we will skip safely
    crm.sync_gcp_organizations(neo4j_session, resources.crm_v1, config.update_tag, common_job_parameters)
github Netflix-Skunkworks / cloudaux / cloudaux / gcp / auth.py View on Github external
:param scopes: scopes to set.  Default is DEFAUL_SCOPES
    :type scopes: ``list``

    :param user_agent: User Agent string to use in requests. Default is None.
    :type http_auth: ``str`` or None

    :return: HTTPLib2 authorized client.
    :rtype: :class: `HTTPLib2`
    """
    if key_file:
        if not scopes:
            scopes = DEFAULT_SCOPES
        creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,
                                                                 scopes=scopes)
    else:
        creds = GoogleCredentials.get_application_default()
    http = Http()
    if user_agent:
        http = set_user_agent(http, user_agent)
    http_auth = creds.authorize(http)
    return http_auth
github ramhiser / serverless-cloud-vision / cloudvision / lib / __init__.py View on Github external
def get_vision_service():
    credentials = GoogleCredentials.get_application_default()
    return discovery.build('vision', 'v1',
                           credentials=credentials,
                           discoveryServiceUrl=API_URL)
github XX-net / XX-Net / gae_proxy / server / lib / google / appengine / ext / remote_api / remote_api_stub.py View on Github external
if not oauth2_parameters:
    if key_file_path:
      if not client.HAS_CRYPTO:
        raise ImportError('Use of a key file to access the Remote API '
                          'requires an encryption library. Please install '
                          'either PyOpenSSL or PyCrypto 2.6 or later.')

      with open(key_file_path, 'rb') as key_file:
        key = key_file.read()
        credentials = client.SignedJwtAssertionCredentials(
            service_account,
            key,
            _OAUTH_SCOPES)
    else:
      credentials = client.GoogleCredentials.get_application_default()
      credentials = credentials.create_scoped(_OAUTH_SCOPES)


    oauth2_parameters = (
        appengine_rpc_httplib2.HttpRpcServerOAuth2.OAuth2Parameters(
            access_token=None,
            client_id=None,
            client_secret=None,
            scope=_OAUTH_SCOPES,
            refresh_token=None,
            credential_file=None,
            credentials=credentials))

  return ConfigureRemoteApi(
      app_id=app_id,
      path=path,
github RadicalDev / GoogleTextToSpeech / transcribe.py View on Github external
def upload_audio(self, speech, sample_rate):
        credentials = GoogleCredentials.get_application_default().create_scoped([SERVICE_URL])

        with open(self.discovery_file, 'r') as f:
            doc = f.read()

        speech_content = base64.b64encode(speech)
        service = discovery.build_from_document(doc, credentials=credentials, http=httplib2.Http())
        service_request = service.speech().recognize(
            body={
                'initialRequest': {
                    'encoding': 'LINEAR16',
                    'sampleRate': sample_rate
                },
                'audioRequest': {
                    'content': speech_content.decode('UTF-8')
                    }
                })
github osteele / ipython-secrets / ipython_secrets.py View on Github external
def iter_credentials():
        try:
            yield keyring.get_keyring().credentials
        except AttributeError:
            pass

        try:
            from oauth2client.client import (ApplicationDefaultCredentialsError,
                                             GoogleCredentials)
            yield GoogleCredentials.get_application_default()
        except (ApplicationDefaultCredentialsError, ImportError):
            pass