1

Let's say I want to obtain an authorization token from google via javascript/python/anything on localhost. How can I do that? After sending a authorization request on "https://accounts.google.com/o/oauth2/auth?..." user has to allow it, but there is no way my script obtained the token back (since google cannot redirect to localhost). Or is it?

Novellizator
  • 13,633
  • 9
  • 43
  • 65
  • 1
    You can't register localhost or an IP as the Redirect URI. There are some workarounds for testing, see this answer http://stackoverflow.com/a/15721876/72176. Do you need this for testing, or is it a different reason? – William Denniss Jul 29 '15 at 20:46
  • @WilliamDenniss I'm more or less just curious about this edge condition and the what if scenarios. I am actually using it in a browser extension and I found some dirty workarounds - so I'm curious if there is some straight way to deal with that, or generally you cannot set up an oauth authorization from desktop&localhost. – Novellizator Jul 29 '15 at 21:20

1 Answers1

0

I have been dealing with OAuth for the last couple of days, and I'm not sure I 100% understand it...but I will try to relay what I have learned.

Here is the code I used to ask a question earlier this week...

index.html

<!doctype html>
<html>
<head>
</head>
<body>
   <p>Tripping all day...</p>
   <p id="output"></p>
   <script src="auth.js"></script>

   <script type="text/javascript">
       function init() {
       console.log('init');
       checkAuth();
       }
   </script>
   <script src="https://apis.google.com/js/client.js?onload=init">    </script>
   <script>
      document.getElementById("output").innerHTML = "Coooooorrrrrraaaaalll";
   </script>
</body>
</html>

auth.js

var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';

var SCOPES = 'email';

function handleAuth(authResult) {
    console.log('handle auth');
    console.log(authResult);
}

function checkAuth() {
    console.log('check auth');
    gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPES, immediate: false, cookie_policy: 'single_host_origin'}, handleAuth);
}

This uses the Gapi javascript client Google provides. When I call gapi.auth.authorize and give it my Client ID I set up in the Developer Console, it shows me the Google account authorization popup, and then I believe that the Gapi object has a method that adds the OAuth token to the Gapi object itself. I didn't include a redirect URI when I set up my credentials, by the way.

After I got the authorize call working, I could then call oauth2.userinfo.get() to get my token to use with their APIs.

var request = gapi.client.oauth2.userinfo.get();

As for the locahost, I used just the IP address of my development server which doesn't have a top level domain attached to it. Localhost may work the same way?

tantangula
  • 314
  • 2
  • 13