Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a login using google in chrome extension

I just recently building an plugin in which I need to integrate Google Login. I searched and found chrome.identity to authenticate user using google account but that does not work well.

So I came across a solution by using this code below

    var manifest = chrome.runtime.getManifest();
    var clientId = encodeURIComponent(manifest.oauth2.client_id);
    var scopes = encodeURIComponent(manifest.oauth2.scopes.join(' '));
    var redirectUri = encodeURIComponent('urn:ietf:wg:oauth:2.0:oob:auto');

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

    var RESULT_PREFIX = ['Success', 'Denied', 'Error'];
    chrome.tabs.create({'url': 'about:blank'}, function(authenticationTab) {
        chrome.tabs.onUpdated.addListener(function googleAuthorizationHook(tabId, changeInfo, tab) {
            if (tabId === authenticationTab.id) {
                
                var titleParts = tab.title.split(' ', 2);
                
                var result = titleParts[0];
                if (titleParts.length == 2 && RESULT_PREFIX.indexOf(result) >= 0) {
                    chrome.tabs.onUpdated.removeListener(googleAuthorizationHook);
                    chrome.tabs.remove(tabId);

                    var response = titleParts[1];
                    switch (result) {
                        case 'Success':
                            // Example: id_token=<YOUR_BELOVED_ID_TOKEN>&authuser=0&hd=<SOME.DOMAIN.PL>&session_state=<SESSION_SATE>&prompt=<PROMPT>
                            console.log("suc:"+response);
                        break;
                        case 'Denied':
                            // Example: error_subtype=access_denied&error=immediate_failed
                            console.log("denied:"+response);
                        break;
                        case 'Error':
                            // Example: 400 (OAuth2 Error)!!1
                            console.log("error:"+response);
                        break;
                    }
                }
            }
        });

        chrome.tabs.update(authenticationTab.id, {'url': url});
    });

In which if I remove v2 from the url variable then it always gives error in the turn with id_token but if I add v2 then its success and return code.

So now I read google documentation which said that now create a post request using client_id and client_secret but I chrome app create credential on google console which does not have client_secret

Now what should I do ? Is there anything that I missed or do wrong here and I also came across one of the chrome extension Screencastify use google login.

Can anyone explain how they do it ?

like image 361
Kushal Jain Avatar asked Jul 07 '17 10:07

Kushal Jain


People also ask

Can I put a password on Chrome extension?

Password Protect Chrome with LockPW Extension The LockPW is an extension for Chrome that allows you to set up password and prompts you to enter the password whenever you open the browser.

How do I pin a Gmail extension in Chrome?

Open the Extensions by clicking the puzzle icon next to your profile avatar. A dropdown menu will appear, showing you all of your enabled extensions. Each extension will have a pushpin icon to the right of it. To pin an extension to Chrome, click the pushpin icon so that the icon turns blue.


1 Answers

There's an official OAuth tutorial here for Chrome extensions/apps which you can refer to.

There's another blog tutorial here:

Step 1: Copy library

You will need to copy the oauth2 library into your chrome extension root into a directory called oauth2.

Step 2: Inject content script

Then you need to modify your manifest.json file to include a content script at the redirect URL used by the Google adapter. The "matches" redirect URI can be looked up in the table above:

"content_scripts": [
  {
    "matches": ["http://www.google.com/robots.txt*"],
    "js": ["oauth2/oauth2_inject.js"],
    "run_at": "document_start"
  }
],

Step 3: Allow access token URL

Also, you will need to add a permission to Google's access token granting URL, since the library will do an XHR against it. The access token URI can be looked up in the table above as well.

"permissions": [
  "https://accounts.google.com/o/oauth2/token"
]

Step 4: Include the OAuth 2.0 library

Next, in your extension's code, you should include the OAuth 2.0 library:

<script src="/oauth2/oauth2.js"></script>

Step 5: Configure the OAuth 2.0 endpoint

And configure your OAuth 2 connection by providing clientId, clientSecret and apiScopes from the registration page. The authorize() method may create a new popup window for the user to grant your extension access to the OAuth2 endpoint.

var googleAuth = new OAuth2('google', {
  client_id: '17755888930840',
  client_secret: 'b4a5741bd3d6de6ac591c7b0e279c9f',
  api_scope: 'https://www.googleapis.com/auth/tasks'
});

googleAuth.authorize(function() {
  // Ready for action
});

Step 6: Use the access token

Now that your user has an access token via auth.getAccessToken(), you can request protected data by adding the accessToken as a request header

xhr.setRequestHeader('Authorization', 'OAuth ' + myAuth.getAccessToken())

or by passing it as part of the URL (depending on the server implementation):

myUrl + '?oauth_token=' + myAuth.getAccessToken();

Note: if you have multiple OAuth 2.0 endpoints that you would like to authorize with, you can do that too! Just inject content scripts and add permissions for all of the providers you would like to authorize with.

And here's the actual github sample using those concepts.

like image 140
noogui Avatar answered Sep 28 '22 10:09

noogui