class Google::Auth::ServiceAccountCredentials

Authenticates requests using Google's Service Account credentials via an OAuth access token.

This class allows authorizing requests for service accounts directly from credentials from a json key file downloaded from the developer console (via 'Generate new Json Key').

cf [Application Default Credentials](goo.gl/mkAHpZ)

Constants

TOKEN_CRED_URI

Attributes

project_id[R]

Public Class Methods

make_creds(options = {}) click to toggle source

Creates a ServiceAccountCredentials.

@param json_key_io [IO] an IO from which the JSON key can be read @param scope [string|array|nil] the scope(s) to access

# File lib/googleauth/service_account.rb, line 59
def self.make_creds(options = {})
  json_key_io, scope = options.values_at(:json_key_io, :scope)
  if json_key_io
    private_key, client_email, project_id = read_json_key(json_key_io)
  else
    private_key = unescape ENV[CredentialsLoader::PRIVATE_KEY_VAR]
    client_email = ENV[CredentialsLoader::CLIENT_EMAIL_VAR]
    project_id = ENV[CredentialsLoader::PROJECT_ID_VAR]
  end
  project_id ||= CredentialsLoader.load_gcloud_project_id

  new(token_credential_uri: TOKEN_CRED_URI,
      audience: TOKEN_CRED_URI,
      scope: scope,
      issuer: client_email,
      signing_key: OpenSSL::PKey::RSA.new(private_key),
      project_id: project_id)
    .configure_connection(options)
end
new(options = {}) click to toggle source
Calls superclass method
# File lib/googleauth/service_account.rb, line 88
def initialize(options = {})
  @project_id = options[:project_id]
  super(options)
end
unescape(str) click to toggle source

Handles certain escape sequences that sometimes appear in input. Specifically, interprets the ā€œnā€ sequence for newline, and removes enclosing quotes.

# File lib/googleauth/service_account.rb, line 82
def self.unescape(str)
  str = str.gsub '\n', "\n"
  str = str[1..-2] if str.start_with?('"') && str.end_with?('"')
  str
end

Public Instance Methods

apply!(a_hash, opts = {}) click to toggle source

Extends the base class.

If scope(s) is not set, it creates a transient ServiceAccountJwtHeaderCredentials instance and uses that to authenticate instead.

Calls superclass method Signet::OAuth2::Client#apply!
# File lib/googleauth/service_account.rb, line 98
def apply!(a_hash, opts = {})
  # Use the base implementation if scopes are set
  unless scope.nil?
    super
    return
  end

  # Use the ServiceAccountJwtHeaderCredentials using the same cred values
  # if no scopes are set.
  cred_json = {
    private_key: @signing_key.to_s,
    client_email: @issuer
  }
  alt_clz = ServiceAccountJwtHeaderCredentials
  key_io = StringIO.new(MultiJson.dump(cred_json))
  alt = alt_clz.make_creds(json_key_io: key_io)
  alt.apply!(a_hash)
end