【发布时间】:2017-03-17 15:03:42
【问题描述】:
我正在编写一个 Chrome 扩展程序,并且一直在尝试使用 chrome.identity.launchWebAuthFlow 向 Google 进行身份验证。我更喜欢 chrome.identity.getAuthToken (它确实有效),因为 getAuthToken 获取当前登录到 Chrome 的用户的令牌——该用户可能登录到多个 Google 帐户。我希望用户能够将特定的 Google 日历连接到我的扩展程序,并且该日历可能属于不同于他们登录 Chrome 的用户。
所以,我一直在尝试使用 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 返回了它,而不是将浏览器重定向到它——我可以从那里继续。
【问题讨论】:
-
请edit 成为主题的问题:包括一个完整 minimal reproducible example 重复该问题。通常,包括一个manifest.json、一些后台和内容脚本。寻求调试帮助的问题(“为什么这段代码不工作?”)必须包括:►期望的行为,►特定问题或错误和►必要的最短代码重现它在问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:“如何创建 minimal reproducible example”、What topics can I ask about here? 和 How to Ask。
-
这个方法对你还有效吗?
-
由于某种原因,我仍然收到错误:未检查的 runtime.lastError:无法加载授权页面。我创建了 Web 应用程序 ID 并按照上述步骤操作。累了两个端点,但无济于事。我在这个线程中遗漏了什么吗?
-
@Armand,我最终没有使用这个 API,所以我不知道这是否仍然有效。
标签: authentication google-chrome-extension google-api oauth-2.0