Nic*_*han 5 google-chrome-extension oauth-2.0 google-oauth google-identity
我在 Chrome 扩展程序中使用身份 API来验证用户身份并向我的后端证明他们是谁。这在大多数情况下都可以正常工作,我使用getAuthToken来获取发送到服务器的 OAuth 访问令牌,服务器用它来确认用户的身份。
唯一的问题是:第一次调用 getAuthToken 时,系统会要求用户从当前登录的帐户列表中选择一个 Google 帐户。此后对 getAuthToken 的任何调用都只是继续重复使用同一 Google 帐户而不提示用户。我想让用户稍后能够选择不同的 Google 帐户。看起来clearAllCachedAuthTokens正是我所需要的 - 而且它有效 - 但只有当所选的Google帐户不是登录Chrome的帐户时。在这种情况下,clearAllCachedAuthTokens 不会执行任何操作。
我发现重置 getAuthToken 锁定的 Google 帐户的唯一方法是让用户退出 Chrome,即使用户选择了登录 Chrome 的 Google 帐户,该方法也能正常工作,这既烦人又尴尬。有没有更好的办法?
对于仍在此处寻找解决方案的人们,我可以通过launchWebAuthFlow
手动使用和处理 OAuth 登录来绕过此限制。
代码片段如下:
const getGoogleAuthCredential = () => {
return new Promise<ReturnType<typeof GoogleAuthProvider.credential>>(
(resolve, reject) => {
const redirectUri = chrome.identity.getRedirectURL();
const authUrl = `https://accounts.google.com/o/oauth2/auth?client_id=${oauthClientId}&response_type=token&redirect_uri=${encodeURIComponent(
redirectUri
)}&scope=${encodeURIComponent(oauthClientScopes.join(" "))}`;
chrome.identity.launchWebAuthFlow(
{ url: authUrl, interactive: true },
(responseUrl) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
}
if (!responseUrl) {
reject("No response URL returned");
return;
}
const params = new URLSearchParams(
new URL(responseUrl).hash.slice(1)
);
const token = params.get("access_token");
if (!token) {
reject("No token found in the response");
return;
}
const credential = GoogleAuthProvider.credential(null, token);
resolve(credential);
}
);
}
);
};
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
归档时间: |
|
查看次数: |
713 次 |
最近记录: |