Why do I get a 404 Error when attempting to get an access_token from google OAuth 2.0?

3,164 views
Skip to first unread message

Roloenusa

unread,
Feb 9, 2012, 3:25:18 PM2/9/12
to oauth...@googlegroups.com

Hello Everyone, 


I'm currently building a OAuth in Ruby on Rails authorization to get email and profile info only.

I can get the code easy using the following:

def authorize
  base
= "https://accounts.google.com/o/oauth2/auth?"
  params
= {
   
:scope => "https://www.googleapis.com/auth/userinfo.profile",
   
:redirect_uri => "http://localhost:3000/oauth/callback/",
   
:client_id => "id",
   
:response_type => 'code'
 
}
  redirect_to base
+ params.to_query
end

However, when I try to get the access token from Google, I get a 404 error:

def callback
  code
= params[:code]
  client_id
= 'id'
  client_secret
= 'secret'
  redirect_uri
= "http://localhost:3000/oauth/callback/"
  http
= Net::HTTP.new('accounts.google.com', 80)
  path
= "https://accounts.google.com/o/oauth2/token?"
  headers
= {'Content-Type'=>"application/x-www-form-urlencoded" }
  parameters
= "code=#{code}&grant_type=authorization_code&client_secret=#{client_secret}&client_id=#{client_id}&redirect_uri=#{redirect_uri}"
  resp
, data = http.post(path,parameters,headers)
end

response code
: 404  data: Google Home | Sign in

The page you requested is invalid.

I'm not entirely sure what the issue might be. I've tried to match with copy+paste the registered callback URL. I've checked my parameters multiple times and I cannot find what could be causing the error.

I'm following the Google documentation and registered with Google with the following information:

Client ID for web applications 
Client ID: id
Client secret: secret
Redirect URIs: http://localhost:3000/oauth/callback/
JavaScript origins: none
Does anyone know what might be causing the 404 response from google?
Thank you!

Roloenusa

unread,
Feb 9, 2012, 8:37:41 PM2/9/12
to oauth...@googlegroups.com
Got it working!

Seems like i was missing a couple of things:

  1. Added the SSL settings for the HTTP request
  2. Send the parameters as the body and not as part of the request
  3. Fixed now how I was sending the content type.

Now it's all working properly!

param = {
  :code => params[:code],
  :client_id => client_id,
  :client_secret => client_secret,
  :redirect_uri => "http://localhost:3000/oauth/callback/",
  :grant_type => 'authorization_code'
}

uri = URI.parse("https://accounts.google.com/o/oauth2/token")
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/x-www-form-urlencoded"
request.body = param.to_query
response = http.request(request)
Reply all
Reply to author
Forward
0 new messages