Last active
March 11, 2017 12:56
-
-
Save dineshsprabu/dbc5ea0ba0ce2ce3b51141fc27497af2 to your computer and use it in GitHub Desktop.
[RUBY][RAILS] Accessing Google API with Oauth2 using the Oauth2 gem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'oauth2' | |
# on the initial action. | |
# Get the client_id and client_secret for your app from | |
# from the developer console of the app to be authenticated. | |
client = OAuth2::Client.new('client_id', 'client_secret', :authorize_url => '/o/oauth2/auth' ,:site =>'https://accounts.google.com') | |
# The redirect uri is the endpoint on our app which can | |
# take the code/access_token sent for further access. | |
a_url = client.auth_code.authorize_url(:redirect_uri => 'http://localhost:8080/oauth2/callback') | |
# The result from previous statement would be an URL and it has | |
# to be appended with scope like this | |
# "&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly" | |
redirect_to a_url | |
# on the callback action. | |
# passing the temp token from google to generate the access token. | |
token_request = $client.auth_code.get_token(params[:code], :redirect_uri => client_redirect_url) | |
access_token = token_request.token # This will be the actual token used on API calls. | |
request_client = OAuth2::AccessToken.new client, access_token, :header_format => "OAuth %s" | |
request_client.get("https://www.googleapis.com/drive/v2/files").body # example API call. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment