107 thoughts on “Authentication and Authorization for Google APIs in Javascript popup window – Tutorial

  1. Thanks to all for your appreciation. I added logout functionality to the code and updated the post appropriately.
    I dont have Window in both home and office, thats why I cant look into IE issue. But will try to fix it somewhere this weekend and update the post.
    Thanks :-)

  2. Thanks for the tutorial.

    Your Demo is not working in Safari. It returns “Welcome undefined”.

    I’m using OSX 10.6.8. The Demo is working in Firefox and Chrome.

  3. Fixed the bug in Safari. It was a missing slash at the end of REDIRECT url: ‘http://localhost:8888/MAMP/web-prototypes/googleapi/oauth/’

    Thanks Bhriv for pointing it out :-)

  4. Saiyasodharan R, I posted this same question in stackoverflow.

    If I get access token the way you suggest, which will make it valid in parent window, can I then make API calls to google apps using the google-api-php-client library?

    Thank you,


  5. @Veronica: Since you are using PHP library, I suggest you to authorize using the functions provided by that library itself rather than falling back to JS for authentication. I believe that is possible. and I replied the same in SO.

  6. I have set up a a Project in the Google APIs Console.
    I have followed your example.
    I have set up client ID.
    I have created a blank page in root directory of Tomcat, and set the corresponding redirect uri
    Redirect URIs: https://localhost:8080/test2.html

    I get this error:
    Secure Connection Failed

    An error occurred during a connection to localhost:8080.

    SSL received a record that exceeded the maximum permissible length.

    (Error code: ssl_error_rx_record_too_long)

    The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    Please contact the website owners to inform them of this problem. Alternatively, use the command found in the help menu to report this broken site.

    What can be the reason????
    Thanks much in advance!!!!

  7. When I redirect to my blank page, I get the buttons, allow access/no thanks. But when I run with your redirect URL and client ID, it doesn’t ask for allow access. Did I do something wrong with my client registration?

  8. “run with your redirect URL” ?? are you also developing in MAMP as I do ? as long as the redirect path given in API console and the actual paths we use match, it should work…

    • I use Apache on windows and IE. Your html code as downloaded works fine. When I change the redirect URL and client ID to my own, I get the allow access question. But with yours I don’t and the token is printed on the window title.

      • As I said already, the actual Redirect URL should match the one you given in the API console and obviously my client ID and yours will be different. So, it wont work out for you with my URL and client ID…

  9. Example works fine but after login google i cant redirect to my url..i want to redirect::
    localhost/oauth/index.php and want every login user on different redirect?? its possible?? if Yes than How??

    Thank in advance..!

  10. in `getUserInfo` function, get the user’s name and then make a redirect like `window.location.href = “localhost/profile/” + user.name;`

        • Its working fine for me in Chrome v22 and I also checked it to be working in IE8. Can you tell me your browser versions ?

        • I have also struggled with the issue, until realizing that my code page was in sub domain of local host, and the redirect page was under localhost (google do not allow for some reason the redirect url to be in a subdomain of localhost). once moving the source page to localhost (to be in the same domain of the redirect page), all was ok.

          it is a sequrity issue to access info from different domains I guess (although it is just domain and subdomain)

  11. With this method, you don’t have to give to Google any secret key. Isn’t it a problem?

    I could take your code, modify it, and for every user who has accepted to use your app, access to their data because Authentification would be invisible since user already have accepted the app.

    With this testApp, maybe it’s not a real problem, but imagine you do the same thing with a well known app. If I see “well known app wants to access to your account”, if I use well known app myself, I will accept the access, and a totally unknown developer will be able to play with my data.

    To sum up, the absence of control of app identity scares me a lot, and I’m surprised that Google don’t talk about it in this page:

    It seems to me a bit too big to believe in. Where am I wrong ?

    • I guess REDIRECT URI serves this purpose. After the auth process, google redirects to the URI in ‘my domain’ that I defined in Google apis console, which you cant access from any random domain because of cross domain policy restrictions.

  12. I think this is one of the most significant info for me. And i am glad reading your article. But should remark on few general things, The web site style is ideal, the articles is really great : D. Good job, cheers

  13. Great Post!
    But how come if i test your code locally with my API data it keeps on showing the “Request for permission” page?
    Your example application works perfect, it only ask for permission once. And afterwards it always delivers the access token (until the token expires)

  14. Nice one thanks for sharing keep it up

    can we do it only using javascript i mean without jquery
    if yes please give me suggestion

    Anand Neema

  15. I see the code the code is nice and i am very happy its working fine but i want more information Like users bithdate,location etc there is any parameter to access that

  16. Hello,
    I am getting this error

    Unable to connect
    Firefox can’t establish a connection to the server at localhost.

    i think this is sumthing to do with redirect URL.

    if i want to run my app locally..then which URL should i mention in the API console.?


  17. And the thing is that.. i am making a chrome extension which uses oauth to access gmail api…so if u know sumthing..abt it..then plz help…thanks

  18. Is it necessary to hide the “redirecturl” for the user once it is successfull. OR is there any problem in showing the right “redirecturl”

  19. Hi,
    Great turorial by the way. I’m very new to JavaScript, ajax and so on. Was just wondering, on a general development level how to get this working on my local machine.

    I’ve followed the example and redirected to an existing site. Which works with the AccessToken etc appearing in the URL, but the popup doesn’t close and the browser window running your code doesn’t get the user info – presume this is due to using some random redirect URL that’s different to where the original page is located.

    So my question is, what should I set the redirect URL to (in the API console and the HTML file) in order to run this from local file on my hard drive? Do I need to setup localhost in order to get this working? or is there an easier way ?

    • Yes, a localhost is mandatory. Google servers cant redirect to a file which is in your local filesystem. They need to be accessed via http, in order for the redirection to work.
      Try WAMP / MAMP / LAMP, which is very easy to install and work with.

  20. I faced the problem to access the document property because of security , Actually If you miss “www” in any of url then it will not work… Fix it that

    • Thank you very much. This solved our problem (at least until now). Our popup windows were not closing and this happened also with similar authentications placed with Twitter, Facebook and Youtube. We added the www. forced to our domain and also in the google api console as redirect url and it worked.

  21. I just finished using the material herein to implement it on my app. Thank you very much for your contribution.


  22. Hey, buddy, this tute is great… n thanks.
    Btw, i get one problem,
    n problem is….

    When page refreshing on that time automatic logout!
    i have some confuson, n how can i manage sesson for useres…

    pls, give some trices or explanations…

    • Good Question. Try this:
      In `login()` function, save the `accesstoken` in a cookie.

      Write `onLoad()` function, get the token from cookie, pass it to validate token.
      * If it returns success, you can proceed as if the user is logged in
      * else leave the page as it is, so the user can log in.

      You can also try experimenting with `expires in` variable.

  23. I’m attempting to perform an OAUTH from a page that is stored locally on my machine (via open file) without a httpd running. Since I have nowhere to host a page I just put together a very basic Google Apps Script and configured my console API to redirect to it and modified your sample code with my clientID and redirect page.

    function doGet() { return HtmlService.createTemplateFromFile(‘dummypage.html’).evaluate(); }

    and then dummypage.html was just
    dummy page

    When I click login it pops up the authenticate/login window and then redirects to my dummy page but it never closes the pop up window and thus your demo code never loads my Google+ profile image.

    If I edit the code
    if (win.document.URL.indexOf(REDIRECT) != -1) {

    by putting a alert(“wait”); above this line and commenting the if statement out. Run the program and give it enough time for Google to respond then click “OK” it just closes the popup and the login.html program just says “Welcome undefined”

    Any ideas? Also, is there any method of authentication that doesn’t require a redirect? How does Google itself do it? I go to google.com or any other apps page and it remembers me without any pop up or button clicks. How can they achieve this?

    • Sorry, I am afraid couldn’t help you, since I have no knowledge with Google Apps Script. But I got few questions, how do you get the access token? will it be given to the Apps Script in some HTTP response?

      and I guess this is how google.com / gmail remembers users. It stores the access token (which they got on first login, which should be through redirection) in cookies, and when the user loads the page, it gets the token from cookies, validates it with an ajax call and if valid, get the user info with it (and probably renew the token, so to get an extended expiry date).

  24. I faced the problem

    This webpage is not available
    Google Chrome’s connection attempt to xxx.com .. Please help me out

  25. how can i redirect to my local machine what is local host what i need to give in that place? Please help me sir

  26. Fixed IE Bug by enclosing popup URL access block within try/catch (tested in IE9) . Please send me the updated code

  27. Thanks for the great work…

    You have solve the IE issue by try and catch.

    But you did not update your full code so many people are taking that code and they still face problem with IE…

    One more time thanks for your great work…

    People who still have problem with IE just check your code that you have try catch block or not??? if not then see the “Step 3: Authentication and Authorization in popup”

  28. window.close is not working in iphone . Do any one have a solution for this.. setTimer, self.close and window.close is not working in Iphone. Where as in other smart phones its working.. Sir pls help me out from this

  29. Hi, first of all, thanks saiy2k for this great tutorial. I meet some problem while applying your tutorial to my website. In my redirect URI in Google APIs console, I use http://application.example.com/blank/ in the field. Then, I create a blank.html and place it in the root folder with my index.html together in hostgator. When I try to access http://application.example.com/blank/ , it gives me “Ïnternal Server Error” but if I use http://application.example.com/blank.html , it brings me to the blank page. I am wondering how and where do you put the blank page .html .

    Sorry, I know this question is kind of stupid but I really need some help.

    Thanks in advance.

  30. Sir,
    Thanks for ur reply. I didnt get any solution . Daily am visitng ur website with more eager that u would have come up with an solution.

    Still waiting..Thanks in advance.

  31. Thanks a lot, really it is good, but the thing is we can’t able to use this in our application, b’cause I don’t want a google popup in raising my application.

    So how to authenticate without the google popup?

    If there any solution, please post that., I am under that difficulty for a week

  32. Hey,
    Your tutorial is fantastic! I really got my login functionality working. One thing though, what if I don’t want the pop up? I just want everything in the same tab. How can I do that? Please enlighten us master!

  33. Pingback: google OAuth2 get url with access_token from the authentication windowCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nod

  34. Hi.
    I using your code to login in my web app. Now, i want using G+ Api to get/post status/comment another. How do I implement it.
    Thank you 😀

  35. Nice post.
    It helped me a lot.

    I need some hints on now how can I read mails and send mails. Is it possible to achieve by writing javascript code?r I need to write server side code?
    Please guide.

  36. hi,
    i need to show the email of logged in user… with this example i am not able to see email id included in the user info that is being console logged… how can i get email id along with the name and details…
    or how can i restrict only users belong to bhavan@sample.com i need only ppl with @sample.com to access my site….

  37. Hi,
    The Demo is working with Chrome, Mozilla, Safari.
    The Demo is also working in IE. But when i run my example it does not run in IE and exception is generated of null reference of window. It runs successfully in other browsers except IE. I have also kept try catch block as per your example. Kindly help!!

  38. This worked like a charm, especially the timer which keeps on polling for the redirect URL.

    Keep up the good work! Cheers!

  39. The tutorial was awesome and helped me understand the google authentication with some hands on. I hosted this in my localhost using apache (that came bundled with mac).
    Everything works perfect when i use localhost/googleAuth/login.html. But if I replace localhost with my IP address, the popup window doesnt close and hence unable to proceed.
    I’m using redirect page http://localhost/googleAuth/AuthLandingPage.html which is a blank page.

    thank you :)

  40. Please i have this problem but in this way i just don’t want the authentification window i want the user can acces without authorisation but i’m stuck i don’t know how to do that ! Please help !!!!

  41. Hello, i just want to know that if User is already login with Google in another tab, now while clicking on SignUP or SignIN button i dont want to popup window i just want to fetch User Detail in back End.
    is it possible?

Leave a Reply

Your email address will not be published. Required fields are marked *