google-chrome-extension - 如何在 Chrome 扩展中使用谷歌创建登录

标签 google-chrome-extension oauth google-oauth google-signin

我最近刚刚构建了一个插件,我需要在其中集成 Google 登录。我搜了一下发现chrome.identity使用谷歌帐户对用户进行身份验证,但效果不佳。
所以我通过使用下面的代码找到了一个解决方案

    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});
    });
如果我删除 v2从 url 变量,然后它总是在轮流中给出错误 id_token但如果我添加 v2然后它的成功和返回码。
所以现在我阅读了谷歌文档,其中说现在使用 client_id and client_secret 创建一个帖子请求但我 chrome 应用程序在没有 client_secret 的谷歌控制台上创建凭据
现在我该怎么办?我在这里有什么遗漏或做错的吗,我还遇到了一个 chrome 扩展 Screencastify使用谷歌登录。
谁能解释他们是如何做到的?

最佳答案

有官方OAuth tutorial here对于您可以引用的 Chrome 扩展程序/应用程序。

还有一个blog tutorial这里:

第一步:复制库

您需要将 oauth2 库复制到您的 chrome 扩展根目录中的一个名为 oauth2 的目录中。

第二步:注入(inject)内容脚本

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

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

第 3 步:允许访问 token URL

此外,您需要向 Google 的访问 token 授予 URL 添加权限,因为该库将针对它执行 XHR。访问 token URI 也可以在上表中查找。
"permissions": [
  "https://accounts.google.com/o/oauth2/token"
]

第 4 步:包含 OAuth 2.0 库

接下来,在您的扩展程序代码中,您应该包含 OAuth 2.0 库:
<script src="/oauth2/oauth2.js"></script>

第 5 步:配置 OAuth 2.0 端点

并通过在注册页面提供 clientId、clientSecret 和 apiScopes 来配置您的 OAuth 2 连接。 authorize() 方法可能会为用户创建一个新的弹出窗口,以授予您的扩展访问 OAuth2 端点的权限。
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 步:使用访问 token

现在您的用户通过 auth.getAccessToken() 获得了访问 token ,您可以通过将 accessToken 添加为请求 header 来请求 protected 数据
xhr.setRequestHeader('Authorization', 'OAuth ' + myAuth.getAccessToken())

或将其作为 URL 的一部分传递(取决于服务器实现):
myUrl + '?oauth_token=' + myAuth.getAccessToken();

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

这是实际的 github sample使用这些概念。

关于google-chrome-extension - 如何在 Chrome 扩展中使用谷歌创建登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968953/

相关文章:

使用 ADAL 的 Azure AD OAuth 身份验证 : what's the resource ID?

authentication - HTTP 基本身份验证、摘要身份验证和 Oauth?

javascript - 无需 OAuth2 重定向/复制和粘贴即可访问私有(private) Google 云端硬盘数据

java - 如何从 Android 访问内置 Google Apps 脚本 'Web App'?

javascript - 按应用程序模式从扩展程序运行网页或本地页面

google-chrome-extension - chrome.tabs.onUpdated.addListener() 被多次调用

html - Google Chrome 扩展程序的 Paypal 按钮

html - (HTML & CSS) 如何在仍然能够检查图像的同时隐藏复选框

javascript - 如何在 javascript 中生成 CMAC-AES

google-drive-api - 使用服务帐户,不使用 PHP 获取任何文件/文件夹列表