Search code examples
google-chrome-extensiongoogle-oauthgmail-api

In chrome extension, how to obtain an access token from a Gmail user other than current Chrome user?


I've created a Chrome extension that works on mail.google.com page and uses gapi to manage emails, and it is not doing well if the Chrome user doesn't match the Gmail user.

The reason is that I'm getting an access_token from chrome.identity.getAuthToken which provides me with a Chrome current user, but not a Gmail one.

I've tried to use gapi.auth2 in my extension to get Gmail users access token, but with no luck:

  • when used from background.js it gets "gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy" error

  • when the same code used from content.js it gets "gapi undefined" error.

Is there a way to get an access_token from a current Gmail user, not a Chrome one?


Solution

  • chrome.identity.launchWebAuthFlow worked for me.

    create oauth2 url:

    var url = 'https://accounts.google.com/o/oauth2/auth' +
            '?client_id=' + clientId +
            '&response_type=token' + 
            '&redirect_uri=' + redirectUri +
            '&login_hint=' + email +
            '&scope=' + scopes;
    

    Where redirectUri is https://<your extension id>.chromiumapp.org/oauth2 and it has to be in the list of Authorized redirect URI (in developers console). I've struggled here a little, because initially I've created "chrome app" credentials and there was no authorized redirect URI's option, so I switched to "web app" credentials.

    email is current user email. Specifying email helps to ommit dialog if user have given permissions already.

    clientId and scopes need to be specified manually, the they wont't be taken automatically from the manifest.

    Then run launchWebAuthFlow:

     chrome.identity.launchWebAuthFlow({
         'url': url,
         'interactive': true
        }, function (redirectedTo) {
           // check errors and get token from redirect url
     });