Python oauth2client.client.GoogleCredentials.get_application_default() Examples

The following are 30 code examples of oauth2client.client.GoogleCredentials.get_application_default(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2client.client.GoogleCredentials , or try the search function .
Example #1
Source File: rpchelper.py    From identity-toolkit-python-client with Apache License 2.0 6 votes vote down vote up
def __init__(self, service_account_email, service_account_key,
               google_api_url, http):
    self.credentials = None
    if service_account_email and service_account_key:
      self.service_account_email = service_account_email
      self.service_account_key = service_account_key
    else:
      self.service_account_email = ''
      self.service_account_key = ''
      try:
        self.credentials = GoogleCredentials.get_application_default() \
            .create_scoped(RpcHelper.GITKIT_SCOPE)
      except Exception as e:
        print('WARNING: unable to retrieve service account credentials.')
    self.google_api_url = google_api_url + 'identitytoolkit/v3/relyingparty/'

    if http is None:
      self.http = httplib2.Http(client.MemoryCache())
    else:
      self.http = http 
Example #2
Source File: client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #3
Source File: gce.py    From flocker with Apache License 2.0 6 votes vote down vote up
def gce_credentials_from_config(gce_credentials_config=None):
    """
    This function creates a proper GCE credentials object either from a passed
    in configuration blob or, if this code is being run on a GCE instance, from
    the default service account credentials associated with the VM.

    :param dict gce_credentials_config: A credentials dict used to authenticate
        against GCE. This should have the same content as the JSON blob you
        download when you create a new key for a service account. If this is
        ``None``, then the instances implicit credentials will be used.

    :returns: A GCE credentials object for use with the GCE API.
    """
    if gce_credentials_config is not None:
        credentials = ServiceAccountCredentials.from_p12_keyfile_buffer(
            service_account_email=gce_credentials_config['client_email'],
            file_buffer=BytesIO(gce_credentials_config['private_key']),
            scopes=[
                u"https://www.googleapis.com/auth/compute",
            ]
        )
    else:
        credentials = GoogleCredentials.get_application_default()
    return credentials 
Example #4
Source File: client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #5
Source File: client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #6
Source File: client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #7
Source File: google.py    From pghoard with Apache License 2.0 6 votes vote down vote up
def get_credentials(credential_file=None, credentials=None):
    if credential_file:
        return GoogleCredentials.from_stream(credential_file)

    if credentials and credentials["type"] == "service_account":
        return ServiceAccountCredentials_from_dict(credentials)

    if credentials and credentials["type"] == "authorized_user":
        return GoogleCredentials(
            access_token=None,
            client_id=credentials["client_id"],
            client_secret=credentials["client_secret"],
            refresh_token=credentials["refresh_token"],
            token_expiry=None,
            token_uri=GOOGLE_TOKEN_URI,
            user_agent="pghoard")

    return GoogleCredentials.get_application_default() 
Example #8
Source File: client.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client.service_account import ServiceAccountCredentials
        data = json.loads(_from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
            data['_class'] == 'ServiceAccountCredentials'):
            return ServiceAccountCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #9
Source File: client.py    From earthengine with MIT License 6 votes vote down vote up
def __init__(self, access_token, client_id, client_secret, refresh_token,
               token_expiry, token_uri, user_agent,
               revoke_uri=GOOGLE_REVOKE_URI):
    """Create an instance of GoogleCredentials.

    This constructor is not usually called by the user, instead
    GoogleCredentials objects are instantiated by
    GoogleCredentials.from_stream() or
    GoogleCredentials.get_application_default().

    Args:
      access_token: string, access token.
      client_id: string, client identifier.
      client_secret: string, client secret.
      refresh_token: string, refresh token.
      token_expiry: datetime, when the access_token expires.
      token_uri: string, URI of token endpoint.
      user_agent: string, The HTTP User-Agent to provide for this application.
      revoke_uri: string, URI for revoke endpoint.
        Defaults to GOOGLE_REVOKE_URI; a token can't be revoked if this is None.
    """
    super(GoogleCredentials, self).__init__(
        access_token, client_id, client_secret, refresh_token, token_expiry,
        token_uri, user_agent, revoke_uri=revoke_uri) 
Example #10
Source File: variant_transform_options.py    From gcp-variant-transforms with Apache License 2.0 6 votes vote down vote up
def validate(self, parsed_args, client=None):
    if not client:
      credentials = GoogleCredentials.get_application_default().create_scoped(
          ['https://www.googleapis.com/auth/bigquery'])
      client = bigquery.BigqueryV2(credentials=credentials)

    project_id, dataset_id, table_id = bigquery_util.parse_table_reference(
        parsed_args.input_table)
    if not bigquery_util.table_exist(client, project_id, dataset_id, table_id):
      raise ValueError('Table {}:{}.{} does not exist.'.format(
          project_id, dataset_id, table_id))
    if table_id.count(TABLE_SUFFIX_SEPARATOR) != 1:
      raise ValueError(
          'Input table {} is malformed - exactly one suffix separator "{}" is '
          'required'.format(parsed_args.input_table,
                            TABLE_SUFFIX_SEPARATOR))
    base_table_id = table_id[:table_id.find(TABLE_SUFFIX_SEPARATOR)]
    sample_table_id = bigquery_util.compose_table_name(base_table_id,
                                                       SAMPLE_INFO_TABLE_SUFFIX)

    if not bigquery_util.table_exist(client, project_id, dataset_id,
                                     sample_table_id):
      raise ValueError('Sample table {}:{}.{} does not exist.'.format(
          project_id, dataset_id, sample_table_id)) 
Example #11
Source File: search.py    From realtime-embeddings-matching with Apache License 2.0 5 votes vote down vote up
def download_artefacts(index_file, bucket_name, gcs_index_location):
  http = Http()
  credentials = GoogleCredentials.get_application_default()
  credentials.authorize(http)
  gcs_services = googleapiclient.discovery.build('storage', 'v1', http=http)
  _download_from_gcs(gcs_services, bucket_name, gcs_index_location, index_file)
  _download_from_gcs(gcs_services, bucket_name,
                     gcs_index_location + '.mapping', index_file + '.mapping') 
Example #12
Source File: labelmaker.py    From professional-services with Apache License 2.0 5 votes vote down vote up
def main(argv):
    # Load label file
    try:
        new_lables = json.load(open(argv[1]))
    except IndexError:
        print("%s <lables.json> required!" %  __file__, file=sys.stderr)
        sys.exit(1)
    except ValueError as err:
        print("%s invalid json: %s" % (sys.argv[1], err), file=sys.stderr)
        sys.exit(1)


    # Pull defaults from metadata
    metadata = get_metadata()
    project, zone = itemgetter(1, 3)(metadata['zone'].split("/"))
    instance_name = metadata['name']

    # Google Creds
    creds = GoogleCredentials.get_application_default()

    # Describe Instance
    conn = discovery.build('compute', 'beta', credentials=creds)
    instance = conn.instances().get(project=project, zone=zone,
                                    instance=instance_name).execute()

    # Label Instance
    label(instance['selfLink'], creds.get_access_token().access_token,
          label_merge(instance['labels'] if 'labels' in instance else {},
                      instance["labelFingerprint"], new_lables))

    # Label Disks
    for i in instance['disks']:
        # Skip local disk
        if 'source' not in i:
            continue
        disk = conn.disks().get(project=project, zone=zone,
                                disk=i['source'].split('/')[-1]).execute()

        label(disk['selfLink'], creds.get_access_token().access_token,
              label_merge(disk['labels'] if 'labels' in disk else {},
                          disk["labelFingerprint"], new_lables)) 
Example #13
Source File: task.py    From realtime-embeddings-matching with Apache License 2.0 5 votes vote down vote up
def upload_artefacts(gcs_index_file):

  http = Http()
  credentials = GoogleCredentials.get_application_default()
  credentials.authorize(http)
  gcs_services = build('storage', 'v1', http=http)

  split_list = gcs_index_file[5:].split('/', 1)
  bucket_name = split_list[0]
  blob_path = split_list[1] if len(split_list) == 2 else None
  _upload_to_gcs(gcs_services, LOCAL_INDEX_FILE, bucket_name, blob_path)
  _upload_to_gcs(gcs_services,
                 LOCAL_INDEX_FILE+'.mapping', bucket_name, blob_path+'.mapping') 
Example #14
Source File: client.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, access_token, client_id, client_secret, refresh_token,
                 token_expiry, token_uri, user_agent,
                 revoke_uri=GOOGLE_REVOKE_URI):
        """Create an instance of GoogleCredentials.

        This constructor is not usually called by the user, instead
        GoogleCredentials objects are instantiated by
        GoogleCredentials.from_stream() or
        GoogleCredentials.get_application_default().

        Args:
            access_token: string, access token.
            client_id: string, client identifier.
            client_secret: string, client secret.
            refresh_token: string, refresh token.
            token_expiry: datetime, when the access_token expires.
            token_uri: string, URI of token endpoint.
            user_agent: string, The HTTP User-Agent to provide for this
                        application.
            revoke_uri: string, URI for revoke endpoint. Defaults to
                        GOOGLE_REVOKE_URI; a token can't be revoked if this
                        is None.
        """
        super(GoogleCredentials, self).__init__(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) 
Example #15
Source File: client.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client import service_account
        data = json.loads(_helpers._from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == 'ServiceAccountCredentials'):
            return service_account.ServiceAccountCredentials.from_json(data)
        elif (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == '_JWTAccessCredentials'):
            return service_account._JWTAccessCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #16
Source File: gcp_agent.py    From citest with Apache License 2.0 5 votes vote down vote up
def make_service(cls, api=None, version=None,
                   scopes=None, credentials_path=None,
                   logger=None):
    """Instantiate a client service instance.

    Args:
      version: [string] The version of the API to use.
      scopes: [string] List of scopes to authorize, or None.
      credentials_path: [string] Path to json file with credentials, or None.
      logger: [Logger] The logger to inject into the agent if not the default.
    Returns:
      Service
    """
    credentials_path = credentials_path or None
    logger = logger or logging.getLogger(__name__)

    if api is None:
      default_api, default_version = cls.default_discovery_name_and_version()
      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) 
Example #17
Source File: utils.py    From kubernetes-bigquery-python with Apache License 2.0 5 votes vote down vote up
def create_bigquery_client():
    """Build the bigquery client."""
    credentials = GoogleCredentials.get_application_default()
    if credentials.create_scoped_required():
            credentials = credentials.create_scoped(BQ_SCOPES)
    http = httplib2.Http()
    credentials.authorize(http)
    return discovery.build('bigquery', 'v2', http=http) 
Example #18
Source File: client.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_application_default():
        """Get the Application Default Credentials for the current environment.

        Raises:
            ApplicationDefaultCredentialsError: raised when the credentials
                                                fail to be retrieved.
        """
        return GoogleCredentials._get_implicit_credentials() 
Example #19
Source File: __init__.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def create_bigquery_object():
    """ Initiates the connection to Google BigQuery. Returns a BigQuery object. """

    if not APP_CREDENTIALS_FILE:
        current_app.logger.error("The GOOGLE_APPLICATIONS_CREDENTIALS variable is undefined, cannot connect to BigQuery")
        raise NoCredentialsVariableException

    if not os.path.exists(APP_CREDENTIALS_FILE):
        current_app.logger.error("The BigQuery credentials file does not exist, cannot connect to BigQuery")
        raise NoCredentialsFileException

    credentials = GoogleCredentials.get_application_default()
    return discovery.build('bigquery', 'v2', credentials=credentials) 
Example #20
Source File: gcp.py    From gcp-audit with Apache License 2.0 5 votes vote down vote up
def create_service(service, version='v1'):
    credentials = GoogleCredentials.get_application_default()
    service = discovery.build(service, version, credentials=credentials)

    return service 
Example #21
Source File: client.py    From alfred-gmail with MIT License 5 votes vote down vote up
def get_application_default():
        """Get the Application Default Credentials for the current environment.

        Raises:
            ApplicationDefaultCredentialsError: raised when the credentials
                                                fail to be retrieved.
        """
        return GoogleCredentials._get_implicit_credentials() 
Example #22
Source File: client.py    From alfred-gmail with MIT License 5 votes vote down vote up
def from_json(cls, json_data):
        # TODO(issue 388): eliminate the circularity that is the reason for
        #                  this non-top-level import.
        from oauth2client import service_account
        data = json.loads(_helpers._from_bytes(json_data))

        # We handle service_account.ServiceAccountCredentials since it is a
        # possible return type of GoogleCredentials.get_application_default()
        if (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == 'ServiceAccountCredentials'):
            return service_account.ServiceAccountCredentials.from_json(data)
        elif (data['_module'] == 'oauth2client.service_account' and
                data['_class'] == '_JWTAccessCredentials'):
            return service_account._JWTAccessCredentials.from_json(data)

        token_expiry = _parse_expiry(data.get('token_expiry'))
        google_credentials = cls(
            data['access_token'],
            data['client_id'],
            data['client_secret'],
            data['refresh_token'],
            token_expiry,
            data['token_uri'],
            data['user_agent'],
            revoke_uri=data.get('revoke_uri', None))
        google_credentials.invalid = data['invalid']
        return google_credentials 
Example #23
Source File: client.py    From alfred-gmail with MIT License 5 votes vote down vote up
def __init__(self, access_token, client_id, client_secret, refresh_token,
                 token_expiry, token_uri, user_agent,
                 revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
        """Create an instance of GoogleCredentials.

        This constructor is not usually called by the user, instead
        GoogleCredentials objects are instantiated by
        GoogleCredentials.from_stream() or
        GoogleCredentials.get_application_default().

        Args:
            access_token: string, access token.
            client_id: string, client identifier.
            client_secret: string, client secret.
            refresh_token: string, refresh token.
            token_expiry: datetime, when the access_token expires.
            token_uri: string, URI of token endpoint.
            user_agent: string, The HTTP User-Agent to provide for this
                        application.
            revoke_uri: string, URI for revoke endpoint. Defaults to
                        oauth2client.GOOGLE_REVOKE_URI; a token can't be
                        revoked if this is None.
        """
        super(GoogleCredentials, self).__init__(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) 
Example #24
Source File: gae_admin_plugin.py    From tensorflow-recommendation-wals with Apache License 2.0 5 votes vote down vote up
def get_svc_conn(self):
    """Returns: a Services Management service object."""
    credentials = GoogleCredentials.get_application_default()
    return build('servicemanagement', 'v1', credentials=credentials) 
Example #25
Source File: gae_admin_plugin.py    From tensorflow-recommendation-wals with Apache License 2.0 5 votes vote down vote up
def get_ae_conn(self):
    """Returns: a App Engine service object."""
    credentials = GoogleCredentials.get_application_default()
    return build('appengine', 'v1', credentials=credentials) 
Example #26
Source File: ml_engine_plugin.py    From tensorflow-recommendation-wals with Apache License 2.0 5 votes vote down vote up
def get_conn(self):
    """Returns a Google MLEngine service object."""
    credentials = GoogleCredentials.get_application_default()
    return build('ml', 'v1', credentials=credentials) 
Example #27
Source File: resources.py    From dagster with Apache License 2.0 5 votes vote down vote up
def __init__(self, config):
        # Use Application Default Credentials to check the
        # GOOGLE_APPLICATION_CREDENTIALS environment variable
        # for the location of the service account key file.
        credentials = GoogleCredentials.get_application_default()

        # See https://github.com/googleapis/google-api-python-client/issues/299 for the
        # cache_discovery=False configuration below
        self.dataproc = build('dataproc', 'v1', credentials=credentials, cache_discovery=False)

        self.config = config

        (self.project_id, self.region, self.cluster_name, self.cluster_config) = (
            self.config.get(k) for k in ('projectId', 'region', 'clusterName', 'cluster_config')
        ) 
Example #28
Source File: auth.py    From cloudaux with Apache License 2.0 5 votes vote down vote up
def _googleauth(key_file=None, scopes=[], user_agent=None):
    """
    Google http_auth helper.

    If key_file is not specified, default credentials will be used.

    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES

    :param key_file: path to key file to use. Default is None
    :type key_file: ``str``

    :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 
Example #29
Source File: utils.py    From kubernetes-bigquery-python with Apache License 2.0 5 votes vote down vote up
def get_credentials():
    """Get the Google credentials needed to access our services."""
    credentials = GoogleCredentials.get_application_default()
    if credentials.create_scoped_required():
            credentials = credentials.create_scoped(SCOPES)
    return credentials 
Example #30
Source File: client.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def get_application_default():
        """Get the Application Default Credentials for the current environment.

        Raises:
            ApplicationDefaultCredentialsError: raised when the credentials
                                                fail to be retrieved.
        """
        return GoogleCredentials._get_implicit_credentials()