本文介绍了使用Chrome身份验证API获取id_token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



为了在我的应用程序中对用户进行身份验证,我需要获得ID_Token(签名的令牌)

有没有办法让OpenID Connect Token与Google Chrome标识API?



感谢您的帮助! 解决方案

这是来自其他主题的答案粘贴





昨天我遇到了同样的问题,自从我找到解决方案后,我可能会分享它,因为它不是那么明显。据我所知Google没有提供直接和书面的方式来做到这一点,但是你可以使用 chrome.identity.launchWebAuthFlow()函数。



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


$ b 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

//使用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( redlinectedTo){
if(chrome.runtime.lastError){
//示例:无法加载授权页面
console.log(chrome.runtime.lastError.message);

else {
var response = redirectedTo.split('#',2)[1];

//示例: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)文档可以在这里找到:



PS:如果您不需要清单中的oauth2部分。您可以放心地忽略它,并提供代码中的标识符和范围。



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

manifest.json

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

background.js

//使用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]; $ (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':
//示例:id_token =< ; YOUR_BELOVED_ID_TOKEN>& authuser = 0& hd =< SOME.DOMAIN.PL&& session_state =< SESSION_SATE>& prompt =< PROMPT>
console.log(response);
打破;
case'Denied':
//示例:error_subtype = access_denied& error = immediate_failed
console.log(response);
休息;
case'Error':
//示例:400(OAuth2错误)!! 1
console.log(response);
休息;
}
}
}
});

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


I am developping a Google Chrome extension, to allow users to authenticate with their Google Accounts, i decided to use Chrome Identity API.

To authenticate the user in my Application i need to get the ID_Token (signed token)

is there a way to get OpenID Connect Token with Google Chrome Identity API ?

Thanks for your help !

解决方案

This is a paste of my answer from the other thread https://stackoverflow.com/a/32548057/3065313

I've came to the same problem yesterday and since I've found a solution, I might as well share it, as it wasn't that obvious. As far as i know Google does not provide a direct and documented way to do this, but you can use the chrome.identity.launchWebAuthFlow() function.

First you should create an Web application credentials in google console and add the following url as a valid Authorized redirect URI: https://<EXTENSION_OR_APP_ID>.chromiumapp.org. The URI does not have to exist, chrome will just catch the redirect to this URL and call your callback function later.

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 (for OpenID Connect) documentation can be found here: https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters

PS: If you don't need the oauth2 section in your manifest. You can safely omit it, and provide the identifiers and scopes in code only.

EDIT:For those interested, you don't need the identity API. You can even access the token using a little trick with tabs API. The code is a little longer, but you have better error messages and control. Keep in mind that in the following example, you need to create Chrome App credentials.

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

这篇关于使用Chrome身份验证API获取id_token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:26
查看更多