Class: Google::Auth::Credentials

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/googleauth/credentials.rb

Overview

Credentials is a high-level base class used by Google's API client libraries to represent the authentication when connecting to an API. In most cases, it is subclassed by API-specific credential classes that can be instantiated by clients.

Important: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to Validate credential configurations from external sources.

Options

Credentials classes are configured with options that dictate default values for parameters such as scope and audience. These defaults are expressed as class attributes, and may differ from endpoint to endpoint. Normally, an API client will provide subclasses specific to each endpoint, configured with appropriate values.

Note that these options inherit up the class hierarchy. If a particular options is not set for a subclass, its superclass is queried.

Some older users of this class set options via constants. This usage is deprecated. For example, instead of setting the AUDIENCE constant on your subclass, call the audience= method.

Example

class MyCredentials < Google::Auth::Credentials
  # Set the default scope for these credentials
  self.scope = "http://example.com/my_scope"
end

# creds is a credentials object suitable for Google API clients
creds = MyCredentials.default
creds.scope  # => ["http://example.com/my_scope"]

class SubCredentials < MyCredentials
  # Override the default scope for this subclass
  self.scope = "http://example.com/sub_scope"
end

creds2 = SubCredentials.default
creds2.scope  # => ["http://example.com/sub_scope"]

Constant Summary collapse

TOKEN_CREDENTIAL_URI =

The default token credential URI to be used when none is provided during initialization.

"https://oauth2.googleapis.com/token".freeze
AUDIENCE =

The default target audience ID to be used when none is provided during initialization.

"https://oauth2.googleapis.com/token".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_creds, options = {}) ⇒ Credentials

Creates a new Credentials instance with the provided auth credentials, and with the default values configured on the class.

Parameters:

  • source_creds (String, Pathname, Hash, Google::Auth::BaseClient)

    The source of credentials. It can be provided as one of the following:

    • The path to a JSON keyfile (as a String or a Pathname)
    • The contents of a JSON keyfile (as a Hash)
    • A Google::Auth::BaseClient credentials object, including but not limited to a Signet::OAuth2::Client object.
    • Any credentials object that supports the methods this wrapper delegates to an inner client.

    If this parameter is an object (Signet::OAuth2::Client or other) it will be used as an inner client. Otherwise the inner client will be constructed from the JSON keyfile or the contens of the hash.

  • options (Hash) (defaults to: {})

    The options for configuring this wrapper credentials object and the inner client. The options hash is used in two ways:

    1. Configuring the wrapper object: Some options are used to directly configure the wrapper Credentials instance. These include:
    • :project_id (and optionally :project) - the project identifier for the client
    • :quota_project_id - the quota project identifier for the client
    • :logger - the logger used to log credential operations such as token refresh.
    1. Configuring the inner client: When the source_creds parameter is a String or Hash, a new Signet::OAuth2::Client is created internally. The following options are used to configure this inner client:
    • :scope - the scope for the client
    • :target_audience - the target audience for the client

    Any other options in the options hash are passed directly to the inner client constructor. This allows you to configure additional parameters of the Signet::OAuth2::Client, such as connection parameters, timeouts, etc.

Raises:



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/googleauth/credentials.rb', line 401

def initialize source_creds, options = {}
  if source_creds.nil?
    raise InitializationError,
          "The source credentials passed to Google::Auth::Credentials.new were nil."
  end

  options = symbolize_hash_keys options
  @project_id = options[:project_id] || options[:project]
  @quota_project_id = options[:quota_project_id]
  case source_creds
  when String, Pathname
    update_from_filepath source_creds, options
  when Hash
    update_from_hash source_creds, options
  else
    update_from_client source_creds
  end
  setup_logging logger: options.fetch(:logger, :default)
  @project_id ||= CredentialsLoader.load_gcloud_project_id
  @env_vars = nil
  @paths = nil
  @scope = nil
end

Instance Attribute Details

#audienceString (readonly)

Returns The target audience ID when issuing assertions. Used only by the assertion grant type.

Returns:

  • (String)

    The target audience ID when issuing assertions. Used only by the assertion grant type.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#clientSignet::OAuth2::Client

The Signet::OAuth2::Client object the Credentials instance is using.



297
298
299
# File 'lib/googleauth/credentials.rb', line 297

def client
  @client
end

#issuerString (readonly)

Returns The issuer ID associated with this client.

Returns:

  • (String)

    The issuer ID associated with this client.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#loggerLogger

Returns The logger used to log credential operations such as token refresh.

Returns:

  • (Logger)

    The logger used to log credential operations such as token refresh.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#project_idString (readonly)

Identifier for the project the client is authenticating with.

Returns:

  • (String)


304
305
306
# File 'lib/googleauth/credentials.rb', line 304

def project_id
  @project_id
end

#quota_project_idString? (readonly)

Identifier for a separate project used for billing/quota, if any.

Returns:

  • (String, nil)


311
312
313
# File 'lib/googleauth/credentials.rb', line 311

def quota_project_id
  @quota_project_id
end

#scopeString+ (readonly)

Returns The scope for this client. A scope is an access range defined by the authorization server. The scope can be a single value or a list of values.

Returns:

  • (String, Array<String>)

    The scope for this client. A scope is an access range defined by the authorization server. The scope can be a single value or a list of values.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#signing_keyString, OpenSSL::PKey (readonly)

Returns The signing key associated with this client.

Returns:

  • (String, OpenSSL::PKey)

    The signing key associated with this client.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#target_audienceString (readonly)

Returns The final target audience for ID tokens returned by this credential.

Returns:

  • (String)

    The final target audience for ID tokens returned by this credential.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#token_credential_uriString (readonly)

Returns The token credential URI. The URI is the authorization server's HTTP endpoint capable of issuing tokens and refreshing expired tokens.

Returns:

  • (String)

    The token credential URI. The URI is the authorization server's HTTP endpoint capable of issuing tokens and refreshing expired tokens.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#universe_domainString

Returns The universe domain issuing these credentials.

Returns:

  • (String)

    The universe domain issuing these credentials.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

#updater_procProc (readonly)

Returns a reference to the Signet::OAuth2::Client#apply method, suitable for passing as a closure.

Returns:

  • (Proc)

    Returns a reference to the Signet::OAuth2::Client#apply method, suitable for passing as a closure.



354
355
356
357
# File 'lib/googleauth/credentials.rb', line 354

def_delegators :@client,
:token_credential_uri, :audience,
:scope, :issuer, :signing_key, :updater_proc, :target_audience,
:universe_domain, :universe_domain=, :logger, :logger=

Class Method Details

.audienceString

The default target audience ID to be used when none is provided during initialization. Used only by the assertion grant type.

Returns:

  • (String)


113
114
115
116
117
# File 'lib/googleauth/credentials.rb', line 113

def self.audience
  lookup_auth_param :audience do
    lookup_local_constant :AUDIENCE
  end
end

.audience=(new_audience) ⇒ Object

Sets the default target audience ID to be used when none is provided during initialization.

Parameters:

  • new_audience (String)


124
125
126
# File 'lib/googleauth/credentials.rb', line 124

def self.audience= new_audience
  @audience = new_audience
end

.default(options = {}) ⇒ Credentials

Creates a new Credentials instance with auth credentials acquired by searching the environment variables and paths configured on the class, and with the default values configured on the class.

The auth credentials are searched for in the following order:

  1. configured environment variables (see env_vars)
  2. configured default file paths (see paths)
  3. application default (see Google::Auth.get_application_default)

Parameters:

  • options (Hash) (defaults to: {})

    The options for configuring the credentials instance. The following is supported:

    • +:scope+ - the scope for the client
    • +"project_id"+ (and optionally +"project"+) - the project identifier for the client
    • +:connection_builder+ - the connection builder to use for the client
    • +:default_connection+ - the default connection to use for the client

Returns:



446
447
448
449
450
451
452
453
454
455
456
# File 'lib/googleauth/credentials.rb', line 446

def self.default options = {}
  # First try to find keyfile file or json from environment variables.
  client = from_env_vars options

  # Second try to find keyfile file from known file paths.
  client ||= from_default_paths options

  # Finally get instantiated client from Google::Auth
  client ||= from_application_default options
  client
end

.env_varsArray<String>

The environment variables to search for credentials. Values can either be a file path to the credentials file, or the JSON contents of the credentials file. The env_vars will never be nil. If there are no vars, the empty array is returned.

Returns:

  • (Array<String>)


195
196
197
# File 'lib/googleauth/credentials.rb', line 195

def self.env_vars
  env_vars_internal || []
end

.env_vars=(new_env_vars) ⇒ Object

Sets the environment variables to search for credentials. Setting to nil "unsets" the value, and defaults to the superclass (or to the empty array if there is no superclass).

Parameters:

  • new_env_vars (String, Array<String>, nil)


219
220
221
222
# File 'lib/googleauth/credentials.rb', line 219

def self.env_vars= new_env_vars
  new_env_vars = Array new_env_vars unless new_env_vars.nil?
  @env_vars = new_env_vars
end

.pathsArray<String>

The file paths to search for credentials files. The paths will never be nil. If there are no paths, the empty array is returned.

Returns:

  • (Array<String>)


230
231
232
# File 'lib/googleauth/credentials.rb', line 230

def self.paths
  paths_internal || []
end

.paths=(new_paths) ⇒ Object

Set the file paths to search for credentials files. Setting to nil "unsets" the value, and defaults to the superclass (or to the empty array if there is no superclass).

Parameters:

  • new_paths (String, Array<String>, nil)


253
254
255
256
# File 'lib/googleauth/credentials.rb', line 253

def self.paths= new_paths
  new_paths = Array new_paths unless new_paths.nil?
  @paths = new_paths
end

.scopeString, ...

The default scope to be used when none is provided during initialization. A scope is an access range defined by the authorization server. The scope can be a single value or a list of values.

Either #scope or #target_audience, but not both, should be non-nil. If #scope is set, this credential will produce access tokens. If #target_audience is set, this credential will produce ID tokens.

Returns:

  • (String, Array<String>, nil)


139
140
141
142
143
144
# File 'lib/googleauth/credentials.rb', line 139

def self.scope
  lookup_auth_param :scope do
    vals = lookup_local_constant :SCOPE
    vals ? Array(vals).flatten.uniq : nil
  end
end

.scope=(new_scope) ⇒ Object

Sets the default scope to be used when none is provided during initialization.

Either #scope or #target_audience, but not both, should be non-nil. If #scope is set, this credential will produce access tokens. If #target_audience is set, this credential will produce ID tokens.

Parameters:

  • new_scope (String, Array<String>, nil)


155
156
157
158
# File 'lib/googleauth/credentials.rb', line 155

def self.scope= new_scope
  new_scope = Array new_scope unless new_scope.nil?
  @scope = new_scope
end

.target_audienceString?

The default final target audience for ID tokens, to be used when none is provided during initialization.

Either #scope or #target_audience, but not both, should be non-nil. If #scope is set, this credential will produce access tokens. If #target_audience is set, this credential will produce ID tokens.

Returns:

  • (String, nil)


170
171
172
# File 'lib/googleauth/credentials.rb', line 170

def self.target_audience
  lookup_auth_param :target_audience
end

.target_audience=(new_target_audience) ⇒ Object

Sets the default final target audience for ID tokens, to be used when none is provided during initialization.

Either #scope or #target_audience, but not both, should be non-nil. If #scope is set, this credential will produce access tokens. If #target_audience is set, this credential will produce ID tokens.

Parameters:

  • new_target_audience (String, nil)


184
185
186
# File 'lib/googleauth/credentials.rb', line 184

def self.target_audience= new_target_audience
  @target_audience = new_target_audience
end

.token_credential_uriString

The default token credential URI to be used when none is provided during initialization. The URI is the authorization server's HTTP endpoint capable of issuing tokens and refreshing expired tokens.

Returns:

  • (String)


92
93
94
95
96
# File 'lib/googleauth/credentials.rb', line 92

def self.token_credential_uri
  lookup_auth_param :token_credential_uri do
    lookup_local_constant :TOKEN_CREDENTIAL_URI
  end
end

.token_credential_uri=(new_token_credential_uri) ⇒ Object

Set the default token credential URI to be used when none is provided during initialization.

Parameters:

  • new_token_credential_uri (String)


103
104
105
# File 'lib/googleauth/credentials.rb', line 103

def self.token_credential_uri= new_token_credential_uri
  @token_credential_uri = new_token_credential_uri
end

Instance Method Details

#duplicate(options = {}) ⇒ Credentials

Creates a duplicate of these credentials. This method tries to create the duplicate of the wrapped credentials if they support duplication and use them as is if they don't.

The wrapped credentials are typically Signet::OAuth2::Client objects and they keep the transient state (token, refresh token, etc). The duplication discards that state, allowing e.g. to get the token with a different scope.

Parameters:

  • options (Hash) (defaults to: {})

    Overrides for the credentials parameters.

    The options hash is used in two ways:

    1. Configuring the duplicate of the wrapper object: Some options are used to directly configure the wrapper Credentials instance. These include:
    • :project_id (and optionally :project) - the project identifier for the credentials
    • :quota_project_id - the quota project identifier for the credentials
    1. Configuring the duplicate of the inner client: If the inner client supports duplication the options hash is passed to it. This allows for configuration of additional parameters, most importantly (but not limited to) the following:
    • :scope - the scope for the client

Returns:



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/googleauth/credentials.rb', line 591

def duplicate options = {}
  options = deep_hash_normalize options

  options = {
    project_id: @project_id,
    quota_project_id: @quota_project_id
  }.merge(options)

  new_client = if @client.respond_to? :duplicate
                 @client.duplicate options
               else
                 @client
               end

  self.class.new new_client, options
end