如何在Chrome扩展程序中使用Google创建登录名 [英] How to create a login using google in chrome extension

查看:92
本文介绍了如何在Chrome扩展程序中使用Google创建登录名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近刚刚构建了一个需要集成Google Login的插件.我搜索并找到 chrome.identity 来使用Google帐户对用户进行身份验证,但效果不佳.

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});
    });

如果我从url变量中删除 v2 ,则总是使用 id_token 依次给出错误,但是如果我添加 v2 ,则成功和返回码.

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.

因此,我现在阅读了Google文档,该文档说现在使用 client_id和client_secret 创建发布请求,但是我在Chrome chrome应用程序上创建了没有 client_secret

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

现在我该怎么办?有什么我想念的地方或做错了吗?我还遇到了一个Chrome扩展程序 Screencastify 使用google登录.

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 ?

推荐答案

此处有官方的 OAuth教程可供您参考的Chrome扩展程序/应用程序.

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

这里还有另一个博客教程:

第1步:复制库

您需要将oauth2库复制到chrome扩展根目录中,并复制到名为oauth2的目录中.

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

第2步:注入内容脚本

然后,您需要修改manifest.json文件,以便在Google适配器使用的重定向URL处包含内容脚本.可以在上表中查找匹配"重定向URI:

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"
  }
],

第3步:允许访问令牌URL

此外,您还需要向Google的访问令牌授予URL添加权限,因为该库将对其进行XHR.访问令牌URI也可以在上表中查找.

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"
]

第4步:包括OAuth 2.0库

接下来,在扩展程序的代码中,您应该包括OAuth 2.0库:

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

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

第5步:配置OAuth 2.0终结点

然后通过从注册页面提供clientId,clientSecret和apiScopes来配置OAuth 2连接.authorize()方法可能会为用户创建一个新的弹出窗口,以向您的扩展程序授予对OAuth2端点的访问权限.

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
});

第6步:使用访问令牌

现在您的用户已经通过auth.getAccessToken()拥有访问令牌,您可以通过将accessToken添加为请求标头来请求受保护的数据

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())

或通过将其作为URL的一部分传递(取决于服务器的实现):

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

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

注意:如果您要授权多个OAuth 2.0端点,也可以这样做!只需注入内容脚本并为要授权的所有提供者添加权限.

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.

这是使用这些概念的实际 github示例.

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

这篇关于如何在Chrome扩展程序中使用Google创建登录名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆