How to create a login using google in chrome extension

Viewed 13644

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 ?

1 Answers
Related