【问题标题】:Get id_token with Chrome Identity API使用 Chrome 身份 API 获取 id_token
【发布时间】:2015-07-01 10:50:34
【问题描述】:

我正在开发一个 Google Chrome 扩展程序,以允许用户使用他们的 Google 帐户进行身份验证,我决定使用Chrome Identity API

要在我的应用程序中验证用户身份,我需要获取 ID_Token(签名令牌)

有没有办法通过 Google Chrome Identity API 获取 OpenID Connect 令牌?

感谢您的帮助!

【问题讨论】:

  • 您是否阅读过文档:developer.chrome.com/apps/identity?另外,请看一两个示例,例如:github.com/GoogleChrome/chrome-app-samples/tree/master/samples/…
  • @Brian 是的,我已经读过了,我也做了同样的事情,现在它工作正常!但结果是一个 access token 仅用于访问 Google API 资源,例如(Drive、Calendar、...),在我的情况下,我需要使用用户的 Google 身份对他进行身份验证我的应用程序。唯一的方法是 OpenID Connect Token :它是一种包含所有用户信息的特殊令牌,它是一个 Signed Token。看看这个:developers.google.com/identity/protocols/OpenIDConnect 感谢您的重播!
  • 来自getProfileUserInfo的令牌对你来说不够吗?
  • @Xan 是的,我在我的其他 Web 应用程序(服务器端)中使用过 OpenID Connect,它非常有帮助,但对于 Chrome 扩展程序它不起作用!我正在尝试使用getProfileUserInfo 获取 Google 用户 ID,它需要特定的 Scope 吗?
  • @ZigMandel 是的,我们需要的不仅仅是电子邮件和经验时间,尤其是签名!

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


【解决方案1】:

这是我在另一个线程https://stackoverflow.com/a/32548057/3065313的答案的粘贴@

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

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

ma​​nifest.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:如果您不需要清单中的 oauth2 部分。您可以放心地省略它,并仅在代码中提供标识符和范围。

编辑: 对于那些感兴趣的人,您不需要身份 API。您甚至可以使用 tabs API 的小技巧来访问令牌。代码有点长,但是你有更好的错误信息和控制。请记住,在以下示例中,您需要创建 Chrome 应用 凭据。

ma​​nifest.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});
});

【讨论】:

  • 嗨@piotr 我面临同样的问题身份api有什么问题。迭代选项设置为 true ,但我无法获取访问令牌。
  • @Amerrnath,您是否尝试完全按照此处所写的方式完成每一点?也许您正尝试从内容脚本访问身份 API,它仅在后台脚本中可用。还要检查您的授权重定向 URI,因为这是非常重要的一步。请记住,在本地安装扩展程序时 会发生变化。很遗憾,我需要更多信息来帮助您。
  • stackoverflow.com/questions/32852920/… 。我已经在这里发布了我的步骤,你可以检查一下。以及 chrome 扩展的重定向 URI 是什么。谢谢。
  • 为什么我应该指定为 Web 应用程序而不是 Chrome 应用程序
  • 没有 access_token 与配置的 launchWebAuthFlow 一起返回。有没有办法同时获得 access_token 和 id_token?
猜你喜欢
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2020-11-13
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多