mnort9
mnort9

Reputation: 1820

How to configure route for oauth callback

I'm using the gem OAuth2 to communicate with Google services. I don't understand how to implement a callback, which receives the response with the OAuth code to get an access token. When I set a breakpoint in the callback method, it never seems to get called.

Here is my code:

Routes:

match '/oauth2/callback' => 'reports#callback'

Actual redirected url:

http://localhost/oauth2/callback?code=111111  

ReportsController:

def new
 client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
         :authorize_url => 'https://accounts.google.com/o/oauth2/auth',
         :token_url => 'https://accounts.google.com/o/oauth2/token'
    })
redirect_to client.auth_code.authorize_url({
        :scope => 'https://www.googleapis.com/auth/analytics.readonly',
        :redirect_uri => 'http://localhost/oauth2/callback',
        :access_type => 'offline'
    }) 
end

def callback
  oauth_code = params[:code]

  # Create access token with oauth_code
end

Upvotes: 2

Views: 6413

Answers (2)

user2108278
user2108278

Reputation: 401

The redirect_url passed to google must match exactly the callback url as seen from client's browser. No problem to use localhost in the url (fotanus sentence about DNS and NAT is wrong). If you are running your container in a different port (e.g. 8080) you have to:

  • Specify the url in google cloud: http://localhost:8080/oauth2/callback

  • Specify that same return url in the client request.

Upvotes: 1

fotanus
fotanus

Reputation: 20116

Google server is trying to access this url http://localhost/oauth2/callback?code=111111 which is not valid.

You need a domain name to use a service like OAuth, because the google server must be able to find your computer over the internet.

To be able to do this from your development machine you should:

  1. Set a name on a known DNS server: The easiest way to do this is through a Dynamic DNS server like dyndns or no-ip

  2. If you are behind a router using NAT, you might need to redirect the requests to your modem on port 80 to your computer: If you don't do this, your modem will receive a package on port 80 from google and will say "not for me", discarding it. You can do this in your modem menu - look for port forwarding or NAT section on it.

Upvotes: 4

Related Questions