我在 Chrome 扩展程序中使用 identity 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);
}
);
}
);
};
希望这有帮助!