0
votes

I am using Ruby on Rails with the Google Drive API (https://github.com/gimite/google-drive-ruby) and I am trying to display data from a spreadsheet on my Google-account in a webpage.

This is the code I use to authorize the application to use my Google Drive account. I have generated credentials for a service account in Google Developers console.

def build_client(credentials)
  client = Google::APIClient.new
  client.authorization = credentials
  client = client.discovered_api('drive', 'v2')
  client
end

Now to access the files I need to start a new session but there is only documentation on how to start a session when you authorize the application via OAuth (https://github.com/gimite/google-drive-ruby#how-to-use) and I am using the credentials generated in Developers Console... what I am trying to figure out is how to start a session when logged in with pre-generated credentials for a service account.

1

1 Answers

0
votes

You should be able to obtain the credentials from your project in console.google.com. From there, we have to update the code in google_drive.rb to authenticate as a service account. The code should be something like:

require 'google/api_client'

## Email of the Service Account #
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

## Path to the Service Account's Private Key file #
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

##
# Build a Drive client instance authorized with the service account
# that acts on behalf of the given user.
#
# @param [String] user_email
#   The email of the user.
# @return [Google::APIClient]
#   Client instance
def build_client(user_email)
    key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
    asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL,
        'https://www.googleapis.com/auth/drive', key)
    client = Google::APIClient.new
    client.authorization = asserter.authorize(user_email)
    client
end

You can find out more information here.