Search code examples
rubyherokuoauthgoogle-api-ruby-client

How can I authorize a Google Service Account without the default credentials file?


I have a Google Service Account that my app uses to retrieve data from Google Analytics.

When I created the account I downloaded a client_secrets file with all the necessary information for authorization via OAuth, and I recorded the path to this file in an environment variable called GOOGLE_APPLICATION_CREDENTIALS as per Google's documentation.

I can now get an authenticated client like this:

authorization = Google::Auth.get_application_default(scopes) 

This method reads the credentials out of the file, which works locally, but my app is hosted on Heroku where file storage is impossible.

The documentation states that I can either provide this file (can’t), run my app on an official Google Service (won’t), or experience an error.

How can I authenticate my service account without the client_secrets file?


Solution

  • I found the answer in the source code of the google-auth-library-ruby gem.

    It turns out that there is another option: take the values from the client_secrets file and put them in environment variables named GOOGLE_ACCOUNT_TYPE, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_EMAIL and GOOGLE_PRIVATE_KEY respectively.

    If these keys are populated, the credentials will load from there. Not a whisper of this in the docs, though.