Two-Legged OAuth with the Google Drive API in Ruby

Google are discontinuing support for the Documents List API, and moving to the Drive API.

The old API supported authentication with a username and password, but that’s not allowed in the new API. Instead, you need to use OAuth for access.

If you want to have server-to-server authentication, without user interaction, you need a “two-legged” OAuth process, where a token is obtained with an encrypted request and then used for future service requests.

One library that used the Documents List API is the Google Drive gem – the gem used to support user/password authentication, but after the switch-off, it’ll only support OAuth.

The code to authenticate with server-to-server OAuth looks like this:

require 'google/api_client'
require "google_drive"

@client = Google::APIClient.new(application_name: 'MyApplication', application_version: '0.0.1')

google_client_email = '140709266912-v466mj2h9vft5c4ehtr7nep6dmn1iq5e@developer.gserviceaccount.com'
google_p12_file = 'MyApplication-71eba82786f1.p12'
google_p12_secret = 'notasecret'

key = Google::APIClient::KeyUtils.load_from_pkcs12(
    google_p12_file,
    google_p12_secret
)

scopes = [
  'https://docs.google.com/feeds/',
  'https://www.googleapis.com/auth/drive',
  'https://spreadsheets.google.com/feeds/'
]

asserter = Google::APIClient::JWTAsserter.new(
    google_client_email,
    scopes,
    key
)

@client.authorization = asserter.authorize

@session = GoogleDrive.login_with_oauth(@client.authorization.access_token)

doc = @session.spreadsheet_by_title('My spreadsheet title')

Then the @session can be used to access documents in Google Drive.

The two crucial bits of config needed are:

— the google client email (140709266912-v466mj2h9vft5c4ehtr7nep6dmn1iq5e@developer.gserviceaccount.com)

— the location of the p12 file (MyApplication-71eba82786f1.p12)

You’ll need to get these from the Google Developer Console.

Create a new project, and then ensure that the Drive API is enabled:

enable-drive-api

Now go to the Credentials page under “APIs and auth”, and use the “Create new Client ID”.

When prompted, choose the “Service Account” type – this allows OAuth access from server-to-server, without user interaction.

creds

This creates a login account which is only for accessing services.

Grab the email address, and use the “Generate new P12 key” button to create and download a public/private keypair.

These are the two things you need in the code above.

One final thing – you’ll need to share any documents that you want to access in your Google Drive with the service account email address that you’ve just created, to grant access permissions.

More background to the process here : https://developers.google.com/identity/protocols/OAuth2ServiceAccount

More about migrating apps to the Drive API here : https://developers.google.com/drive/web/migration

Leave a Reply

Your email address will not be published.