可以使用chrome.identity.launchWebAuthFlow对Google API进行身份验证吗?

问题描述:

我正在编写Chrome扩展,并一直试图使用chrome.identity.launchWebAuthFlow向Google进行身份验证。我更喜欢chrome.identity.getAuthToken(它可以工作),因为getAuthToken获取当前登录到Chrome的用户的令牌 - 可能会登录到多个Google帐户。我希望用户能够将特定的Google日历连接到我的扩展程序,并且该日历可能属于与他们登录Chrome时不同的用户。可以使用chrome.identity.launchWebAuthFlow对Google API进行身份验证吗?

所以,我一直试图做到这一点与chrome.identity.launchWebAuthFlow和通常失败的redirect_uri不匹配。我已经尝试了几乎所有可以在Google API开发人员控制台中设置的凭据类型。 (“Chrome应用程序”似乎是正确的,但我也尝试过Web应用程序,其他和iOS)。我尝试过使用chrome.extension.getURL('string')和chrome.app.getRedirectURL ('string')作为我的redirect_uri。

我试用了https://stackoverflow.com/questions/40384255/oauth2-angular-chrome-extension中提到的示例应用程序,但无法使其工作。

我有一个怀疑,我正在尝试做一些事情,要么以前被允许,不再是或者从来没有工作过。

这里是我的代码的例子,但我想我的问题是真正的API,开发者控制台 - 我不明白的方式来建立一个配置,将延期工作:

var auth_url = 'https://accounts.google.com/o/oauth2/v2/auth'; 
    var client_key = *[client id from API dev console]* 
    var auth_params = { 
         client_id: client_key, 
         redirect_uri: chrome.identity.getRedirectURL("oauth2.html") 
         scope: 'https://www.googleapis.com/auth/calendar' 
         }; 
    auth_url += '?' + $.param(auth_params); 

    chrome.identity.launchWebAuthFlow({url: auth_url, interactive: true}, function(token) { console.log(token); }); 

(我也曾尝试https://accounts.google.com/o/oauth2/auth端点。)

解决方案:

阅读接受的答案后,我结束了与此:

var auth_url = 'https://accounts.google.com/o/oauth2/auth'; 
var client_id = '[client ID from console]'; 
var redirect_url = chrome.identity.getRedirectURL("oauth2.html"); 
var auth_params = { 
    client_id: client_id, 
    redirect_uri: redirect_url, 
    response_type: 'token', 
    scope: 'profile' 
}; 
auth_url += '?' + $.param(auth_params); 
console.log(auth_url); 
chrome.identity.launchWebAuthFlow({url: auth_url, interactive: true}, function(responseUrl) { console.log(responseUrl); }); 

responseUrl是我的带参数的redirect_uri - 所以Google oauth返回的是,而不是将浏览器重定向到它 - 我可以从那里继续。

+0

请将该问题置于主题上:包括一个**完整的** [mcve],可以复制问题。通常包括一个* manifest.json *,一些背景*和*内容脚本。寻求调试帮助的问题(“**为什么不是这个代码工作?”)必须包括:►期望的行为,►特定问题或错误*和*►在问题中重现问题所需的最短代码**本身**。没有明确问题陈述的问题对其他读者无益。请参阅:“**如何创建[mcve] **”,[我可以在此处询问哪些主题?](http://stackoverflow.com/help/on-topic)和[问]。 – Makyen

+0

这种方法仍然适合你吗? – seesoe

要获得Angular sample运行,我需要:

  1. 与建立在谷歌开发者控制台我自己的Web应用程序客户端ID授权重定向https://bcgajjfnjjgadphgiodlifoaclnemcbk.chromiumapp.org/oauth2

  2. 复制客户端ID的URI成示例的config.json文件。

的呼叫样品中获得redirectURI就像是chrome.identity.getRedirectURL("oauth2"),字符串参数被追加到基于扩展ID的URL的结尾。

+0

我会尽力看看我能否做出这项工作并尽快接受您的答案。我至少已设法输入您在Google开发者控制台中指定格式的授权重定向URI。 我最终以不同的方式构建我的应用 - 扩展只与“我们的”服务器直接通信,“我们”的服务器代表用户通过oauth2使用Google API。无论如何,我们都需要服务器到服务器的通信。 –

+0

谢谢!我还没有回到角度样本,但你的提示帮助我克服了这个难题。 (可能Google也更新了他们的chrome.identity文档,因为现在很清楚,它不会像我几个月前所想的那样)。除了开发者控制台问题之外,我还需要为auth网址添加一个“response_type”参数。 当使用chrome.identity.getRedirectURL('whatever')URL作为redirect_uri时,您传递给启动WebAuthFlow的回调获取带查询参数的redirect_uri作为其单个参数。 –