Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Last active August 6, 2018 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahemoff/3814a81f5d57ba0ae826ec4c26a3b27e to your computer and use it in GitHub Desktop.
Save mahemoff/3814a81f5d57ba0ae826ec4c26a3b27e to your computer and use it in GitHub Desktop.
Verifying Google OAuth auth code on the back-end

This is the "missing Ruby example" for the ID flow example at https://developers.google.com/identity/sign-in/web/server-side-flow.

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(
URI('https://www.googleapis.com/oauth2/v4/token'),
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
Rails.logger.info "OAuth auth code succeeded"
puts result.to_json
else
Rails.logger.info "OAuth auth code failed #{result.code}\n#{result.body}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment