How to configure route for oauth callback

I use gem OAuth2 to communicate with Google services. I do not understand how to implement a callback that receives a response with OAuth code in order to get an access token. When I set a breakpoint in the callback method, it never calls the call.

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 
+2
source share
2 answers

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

To use a service such as OAuth, a domain name is required because the google server must be able to find your computer over the Internet.

To do this from your development machine, you must:

  • Set a name on a known DNS server: The easiest way to do this is through a dynamic DNS server, such as dyndns or no-ip

  • If you are behind a router using NAT , you may need to redirect requests for your modem to port 80 on your computer . If you do not, the modem will receive a packet on port 80 from Google and say "not for me", dropping it. You can do this in your modem - look for port forwarding or the NAT section on it.

+4
source

The redirect_url passed to google must exactly match the callback url, as seen from the client’s browser. There is no problem using localhost in the url (fotanus suggestion about DNS and NAT is wrong). If you are using your container in another port (e.g. 8080), you should:

  • Specify the URL in the Google Cloud: http://localhost:8080/oauth2/callback

  • Provide the same return URL in the client request.

+1
source

Source: https://habr.com/ru/post/1483655/


All Articles