Skip to content

Instantly share code, notes, and snippets.

@selvan
Created January 23, 2013 08:42
Show Gist options
  • Save selvan/4603219 to your computer and use it in GitHub Desktop.
Save selvan/4603219 to your computer and use it in GitHub Desktop.
Geting new access token using refresh token - Google oauth2
### Method 1
gem install oauth2
require 'oauth2'
client = OAuth2::Client.new(GOOGLE_KEY, GOOGLE_SECRET, {:site => 'https://accounts.google.com', :authorize_url => "/o/oauth2/auth", :token_url => "/o/oauth2/token"})
response = OAuth2::AccessToken.from_hash(client, :refresh_token => REFRESH_TOKEN).refresh!
puts response.token
puts response.expires_at
### Methdo 2
gem install rest-client
## http://stackoverflow.com/questions/12572723/rails-google-client-api-unable-to-exchange-a-refresh-token-for-access-token
def refresh_token
data = {
:client_id => GOOGLE_KEY,
:client_secret => GOOGLE_SECRET,
:refresh_token => REFRESH_TOKEN,
:grant_type => "refresh_token"
}
response = ActiveSupport::JSON.decode(RestClient.post "https://accounts.google.com/o/oauth2/token", data)
if response["access_token"].present?
# Save your token
else
# No Token
end
rescue RestClient::BadRequest => e
# Bad request
rescue
# Something else bad happened
end
@xxswingxx
Copy link

Thanks a lot for making this public! Very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment