Skip to content

Instantly share code, notes, and snippets.

@mahemoff mahemoff/

Last active Aug 6, 2018
What would you like to do?
Verifying Google OAuth auth code on the back-end

This is the "missing Ruby example" for the ID flow example at

It's easy enough to get an auth code like "4/BlahBlahBlah...", but I couldn't find any working examples on how to exchange it for the access code and encoded ID.

To use this, you need to access Google's API console, and under "credentials" establish a client ID and secret, which should go in your environment. (Most examples will use the "secrets.json" file, but I don't want to keep a separate config file for every platform, so it's better to put them in something like Rails' secret.yml or Figaro).

The auth_code is obtained from your web or native client using Google's front-end libraries. The client posts it to your own back-end, which does the exchange and verifies+stores the result. Note the redirect URI must be configured in Google's "credentials" console, otherwise the call will fail (even though it serves no purpose in this context; it's only needed for a non-JavaScript web app).

class GoogleOAuth
# example code: 4/BlahBlah... (112 chars)
def self.exchange_auth_code(auth_code)
result = Net::HTTP.post_form(
code: auth_code,
client_id: ENV['GOOGLE_CLIENT_ID'],
client_secret: ENV['GOOGLE_CLIENT_SECRET'],
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000'
if result.code==200 "OAuth auth code succeeded"
puts result.to_json
else "OAuth auth code failed #{result.code}\n#{result.body}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.