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

  1. Hi,
    Thanks for the post. I have used it it works perfect for my application.

    I need to users to be logged out of google when they logout of my application. How do I achieve this? Please help.

  2. 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 :-)

  3. 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.

  4. 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 :-)

  5. 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,

    Veronica

  6. @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.

  7. 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!!!!

  8. 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?

  9. “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…

  10. 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..!

  11. 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)

  12. 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:
    https://developers.google.com/accounts/docs/OAuth2UserAgent

    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.

  13. 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

  14. 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)

  15. 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

    Cheers
    Anand Neema

  16. 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

  17. 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.?

    Thanks

  18. 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

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

  20. 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.

  21. 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.

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

    Regards
    Rodrigo

  23. 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.

  24. 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).

  25. I faced the problem

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

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

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

  28. 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”

  29. 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

  30. 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.

  31. 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.

  32. 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

  33. Hi…
    First of all..great blog..was very helpful and clear. Thanks for that.
    Can you direct me as to how to integrate Calendar and mail into this web page along with the user name.

  34. THis code is not working in IE. I have checked it on IE8. I have used try and catch blocks also but still its not working. Please help

  35. It doesn’t work for me because (from reading the log) the script is only looping through once when checking for the redirect url. I even when and copied the javascript from the working example. Here’s my (unfinished) code.

    Youtube Web App

    var OAUTHURL = ‘https://accounts.google.com/o/oauth2/auth?’;
    var VALIDURL = ‘https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=’;
    var SCOPE = ‘https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtube.upload‘;
    var CLIENTID = ’260568508745.apps.googleusercontent.com’;
    var REDIRECT = ‘https://sites.google.com/site/kiontupper/youtube-browser’
    var LOGOUT = ‘http://accounts.google.com/Logout’;
    var TYPE = ‘token’;
    var _url = OAUTHURL + ‘scope=’ + SCOPE + ‘&client_id=’ + CLIENTID + ‘&redirect_uri=’ + REDIRECT + ‘&response_type=’ + TYPE;
    var acToken;
    var tokenType;
    var expiresIn;
    var user;
    var loggedIn = false;

    function login() {
    var win = window.open(_url, “windowname1″, ‘width=800, height=600′);

    var pollTimer = window.setInterval(function() {
    try {
    console.log(win.document.URL);
    if (win.document.URL.indexOf(REDIRECT) != -1) {
    window.clearInterval(pollTimer);
    var url = win.document.URL;
    acToken = gup(url, ‘access_token’);
    tokenType = gup(url, ‘token_type’);
    expiresIn = gup(url, ‘expires_in’);
    win.close();

    validateToken(acToken);
    }
    } catch(e) {
    }
    }, 500);
    }

    function validateToken(token) {
    $.ajax({
    url: VALIDURL + token,
    data: null,
    success: function(responseText){
    getUserInfo();
    loggedIn = true;
    $(‘#loginText’).hide();
    $(‘#logoutText’).show();
    },
    dataType: “jsonp”
    });
    }

    function getUserInfo() {
    $.ajax({
    url: ‘https://www.googleapis.com/oauth2/v1/userinfo?access_token=’ + acToken,
    data: null,
    success: function(resp) {
    user = resp;
    console.log(user);
    $(‘#uName’).text(‘Welcome ‘ + user.name);
    $(‘#imgHolder’).attr(‘src’, user.picture);
    },
    dataType: “jsonp”
    });
    }

    //credits: http://www.netlobo.com/url_query_string_javascript.html
    function gup(url, name) {
    name = name.replace(/[\[]/,”\\\[").replace(/[\]]/,”\\\]”);
    var regexS = “[\\#&]“+name+”=([^&#]*)”;
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    if( results == null )
    return “”;
    else
    return results[1];
    }

    Login

    //document.write = (“Type a video ID* in the box below. If you want to see another video, use the back button to go back to this page.Watch*Look at the url (www.youtube.com/watch?v=kkakslSKkfjie, ‘kkakslSKkfjie’ is the id; http://www.youtube.com/watch?v=kkakslSKkfjie&list=kdjahtedKslfeTDST, ‘kkakslSKkfjie’ is still the id)Note: The above example will not lead to an actuall video page, it was just be randomly typing letters.”)

  36. 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!

  37. 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

  38. 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 :D

  39. 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.

  40. Hi, first of all thanks for providing this tutorial. There is no issues with your approach. After successful authentication from google, redirect page is showing for some time in popup window, is there any approach to avoid this ? i,e in popup window redirect page should not be visible to the users.

  41. Really good guide, I’m starting with a screencast about how to use an API in Rails using html and also I’m going to implement authentication it’s a good idea using google oauth, thanks for the shared code, regards

  42. Very goog example and explanation for Google OAuth. I have a Problem with Popups. The HbbTV standards for SmartTV don’t allow Popups (e.g. the main Page will loose the focus). Maybe you know a workaround to user Google OAuth without Popup, like an own Login form? Hope someone knows how to. Thank you a lot :)

  43. Wonderful illustration of the user-agent oauth validation.
    I must say, though, this is a perfect example of “No good deed goes unpunished” :-)
    I suppose all the questions means this is popular, but they probably will force you to think twice next time you want to post a new blog entry.

  44. I see the code the code is nice and i am very happy its working fine but i want more information Like users email there is any parameter to access

  45. This is very useful post. It works fine for me. But i got the same issue with IE. One more question , How to implement Signin with Google Apps account in the same way ???

  46. How to get permanent access. It ask always to login. Is there any way to get and store token in database to get data net time…Thanks

  47. Isn’t what you doing in the pollTimer function against the same origin policies? Essentially you can not access the document of a window opened in a domain other than you are on. Isn’t it? When i try doing this, i get JS error.

  48. Hi, thanks for this great post, the regular expression do not match all possible case, it hit me, something more simple like this: name + “=([^\&]*)?” could work.

    regards

  49. Hi,
    Thx a lot for your post, I was stuck in my implementation with the waiting part in the popup :)

    You save my day!

    yannig

  50. Pingback: [Google OAuth] Authentication and Authorization for Google APIs in Javascript popup window | Jinny's Blog

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>