Question

I am building a web app requiring access to a users gmail using Oauth2. I registered my app and can get the initial code, but can't figure out how to get an access token and refresh code afterwards.

First, the user is sent to a secure google page to put in user name/password. Afterwards, google redirects the user to something like:

127.0.0.1/oauth2callback?code=4/ux5gNj-_mIu4DOD_gNZdjX9E

I have this method below to handle the redirect. The code is sent with other info in a post request back to Google in exchange for a access token and refresh code. Unfortunately the response in the bottom has blank body. What am I doing wrong? Do I need to call another function on response to get the access token?

def oauth2callback
  require "uri"
  require "net/http"

  uri = URI.parse("https://accounts.google.com/o/oauth2/token")
  http = Net::HTTP.new(uri.host, uri.port)

  request = Net::HTTP::Post.new(uri.request_uri)
  request.set_form_data(      
  {'code'=>params[:code],
  'client_id' => CLIENT_ID,
  'client_secret' => CLIENT_SECRET,
  'redirect_uri' => '127.0.0.1:3000/oauth2callback',
  'grant_type' => 'authorization_code'})

  http.use_ssl = true
  response = http.request(request)
  #response.body() is blank
end
Was it helpful?

Solution

Your redirect uri must match exactly the one, the user got redirected to. In your case this is 127.0.0.1/oauth2callback without :3000.

However, I believe that for Google both uri's needn't to be identical, but at least defined in the developer console, so maybe you could try adding 127.0.0.1:3000/oauth2callback to your developer console.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top