使用Chrome Identity API获取id_token

use*_*584 7 google-chrome-extension google-oauth google-chrome-app openid-connect

我正在开发Google Chrome扩展程序,以便用户通过自己的Google帐户进行身份验证,我决定使用Chrome Identity API.

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

有没有办法通过谷歌Chrome Identity API获得OpenID Connect Token?

谢谢你的帮助 !

Pio*_*ech 11

这是我从其他线程回答的粘贴/sf/answers/2278364021/

我昨天遇到了同样的问题,因为我找到了一个解决方案,我不妨分享一下,因为它并不那么明显.据我所知,谷歌没有提供直接和记录的方式来做到这一点,但你可以使用该chrome.identity.launchWebAuthFlow()功能.

首先,您应该在谷歌控制台中创建一个Web应用程序凭据,并添加以下URL作为有效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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

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

PS:如果你的清单中不需要oauth2部分.您可以安全地省略它,并仅在代码中提供标识符和范围.

编辑:对于那些感兴趣的人,您不需要身份API.您甚至可以使用制表符API的小技巧来访问令牌.代码有点长,但您有更好的错误消息和控制.请注意,在以下示例中,您需要创建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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

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});
});
Run Code Online (Sandbox Code Playgroud)