Skip to content

Instantly share code, notes, and snippets.

@JasonLunn
Created May 4, 2017 01:33
Show Gist options
  • Save JasonLunn/a96a9b1143d9b770359938a55d40709f to your computer and use it in GitHub Desktop.
Save JasonLunn/a96a9b1143d9b770359938a55d40709f to your computer and use it in GitHub Desktop.
##
# For use with a Rails app that uses the omniauth-google-oauth2 gem (e.g. https://github.com/JasonLunn/oauth2-protected-api)
#
# To run:
# SERVICE_ACCOUNT_CREDENTIALS_FILENAME=/path/to/service-account-credentials.json bundle exec ruby ./gist-client.rb
#
# Where /path/to/service-account-credentials.json contains service account credentials downloaded from
# https://console.developers.google.com/apis/credentials
require 'googleauth'
require 'net/http'
file = File.open ENV['SERVICE_ACCOUNT_CREDENTIALS_FILENAME'], 'r'
sac = Google::Auth::ServiceAccountCredentials.make_creds json_key_io: file, scope: %w(email profile)
sac.fetch_access_token!
protected_content_url = 'http://localhost:3000/protected'
protected_content_uri = URI.parse protected_content_url
Net::HTTP.start(protected_content_uri.hostname, protected_content_uri.port) {|http|
# Make an unauthenticated request for the protected content
initial_request = Net::HTTP::Get.new protected_content_uri
initial_response = http.request(initial_request)
redirect_location = initial_response['location']
# Unauthenticated requests will be redirected to a login controller
login_uri = URI.parse redirect_location
login_request = Net::HTTP::Get.new login_uri
login_response = http.request(login_request)
cookie = login_response['set-cookie']
# Parse the redirection URL to find the state and redirect_uri parameters
redirect_location = login_response['location']
location_uri = URI.parse redirect_location
query_parameters = Hash[ location_uri.query.split( '&' ).map { |s| s.split '=' } ]
state = query_parameters[ 'state' ]
redirect_uri = URI.parse URI.decode query_parameters['redirect_uri']
# Invoke the callback uri with the access_token and the state, using the session identified by the cookie
redirect_uri.query = "state=#{state}&access_token=#{sac.access_token}"
callback_request = Net::HTTP::Get.new redirect_uri
callback_request['Cookie'] = cookie
callback_response = http.request(callback_request)
cookie = callback_response['set-cookie']
# Follow the redirect back to the protected content
redirect_location = callback_response['location']
authenticated_request = Net::HTTP::Get.new URI.parse redirect_location
authenticated_request['Cookie'] = cookie
authenticated_response = http.request(authenticated_request)
puts authenticated_response.body
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment