google-chrome-extension - 使用Chrome Identity API获取id_token

标签 google-chrome-extension google-oauth google-chrome-app openid-connect

我正在开发Google Chrome扩展程序,以允许用户通过其Google帐户进行身份验证,因此我决定使用Chrome Identity API

要在我的应用程序中对用户进行身份验证,我需要获取ID_Token(签名 token )

有没有一种方法可以通过Google Chrome Identity API获取OpenID Connect token ?

谢谢你的帮助 !

最佳答案

这是我从其他线程https://stackoverflow.com/a/32548057/3065313的答案中粘贴的内容

昨天我遇到了同样的问题,自从找到解决方案以来,我不妨分享一下,因为它并不那么明显。据我所知,Google并没有提供直接且有据可查的方式来执行此操作,但是您可以使用chrome.identity.launchWebAuthFlow()函数。

首先,您应该在Google控制台中创建 Web应用程序凭据,然后将以下网址添加为有效的Authorized redirect URI:https://<EXTENSION_OR_APP_ID>.chromiumapp.org。 URI不必存在,chrome只会捕获到该URL的重定向,并在以后调用您的回调函数。

manifest.json :

{
  "manifest_version": 2,
  "name": "name",
  "description": "description",
  "version": "0.0.0.1",
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "identity"
  ],
  "oauth2": {
    "client_id": "<CLIENT_ID>.apps.googleusercontent.com",
    "scopes": [
      "openid", "email", "profile"
    ]
  }
}

background.js :

// Using chrome.identity
var manifest = chrome.runtime.getManifest();

var clientId = encodeURIComponent(manifest.oauth2.client_id);
var scopes = encodeURIComponent(manifest.oauth2.scopes.join(' '));
var redirectUri = encodeURIComponent('https://' + chrome.runtime.id + '.chromiumapp.org');

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

chrome.identity.launchWebAuthFlow(
    {
        'url': url, 
        'interactive':true
    }, 
    function(redirectedTo) {
        if (chrome.runtime.lastError) {
            // Example: Authorization page could not be loaded.
            console.log(chrome.runtime.lastError.message);
        }
        else {
            var response = redirectedTo.split('#', 2)[1];

            // Example: id_token=<YOUR_BELOVED_ID_TOKEN>&authuser=0&hd=<SOME.DOMAIN.PL>&session_state=<SESSION_SATE>&prompt=<PROMPT>
            console.log(response);
        }
    }
);

可以在以下位置找到Google OAuth2 API(用于OpenID Connect)文档:https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters

PS:如果您不需要 list 中的oauth2部分。您可以安全地忽略它,而仅在代码中提供标识符和范围。

编辑:
对于那些感兴趣的人,您不需要身份API。您甚至可以使用带有Tabs API的小技巧来访问 token 。该代码稍长一些,但是您可以得到更好的错误消息和控制。请注意,在以下示例中,您需要创建 Chrome应用凭据。

manifest.json :

{
  "manifest_version": 2,
  "name": "name",
  "description": "description",
  "version": "0.0.0.1",
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "tabs"
  ],
  "oauth2": {
    "client_id": "<CLIENT_ID>.apps.googleusercontent.com",
    "scopes": [
      "openid", "email", "profile"
    ]
  }
}

background.js :

// Using chrome.tabs
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/auth' + 
          '?client_id=' + clientId + 
          '&response_type=id_token' + 
          '&access_type=offline' + 
          '&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(response);
                    break;
                    case 'Denied':
                        // Example: error_subtype=access_denied&error=immediate_failed
                        console.log(response);
                    break;
                    case 'Error':
                        // Example: 400 (OAuth2 Error)!!1
                        console.log(response);
                    break;
                }
            }
        }
    });

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

关于google-chrome-extension - 使用Chrome Identity API获取id_token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31159206/

相关文章:

google-chrome - gmail api返回查询参数之外的电子邮件

html - 如何为 Google Chrome 和 Google Tasks 网站创建用户样式?

oauth-2.0 - Google 刷新 token 生命周期

javascript - 如何在 Chrome 应用程序中包含 jQuery?

javascript - 无法从弹出窗口访问网页 DOM; console.logs不显示

javascript - onMessage 未在 Chrome 扩展程序上执行

youtube - 使用JavaScript将视频上传到youtube,而无需登录google

reactjs - 发送到我的服务器时,“使用Google登录” JWT无效

html - Chrome 打包应用程序 - 使用多个 HTML 文件

android - 如何运行 chrome 工具而不是浏览器