You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome扩展中获取与Apps Script一致的Google OpenID Connect令牌?

问题解答

核心结论

你拿到的两种令牌完全不同:

  • ScriptApp.getIdentityToken()返回的是ID Token(JWT格式,包含用户身份标识信息),专门用于身份验证,能被https://oauth2.googleapis.com/tokeninfo?id_token={token}端点验证。
  • chrome.identity.getAuthToken()默认返回的是Access Token,用于授权访问Google的各类API,不具备身份验证的结构,因此无法通过ID Token的验证逻辑。

代码遗漏的点

你没有在Chrome扩展的授权流程中指定要获取ID Token的配置,默认只会请求Access Token,导致拿到的令牌不符合后端验证要求。

如何在Chrome扩展中获取ID Token(与ScriptApp.getIdentityToken()一致)

1. 配置manifest.json

确保扩展的manifest.json中包含identity权限和正确的OAuth2配置,必须添加openid scope(获取ID Token的必要条件):

{
  "manifest_version": 3,
  "name": "你的扩展名称",
  "version": "1.0",
  "permissions": ["identity"],
  "oauth2": {
    "client_id": "你的Google OAuth客户端ID",
    "scopes": [
      "openid",
      "email",
      "profile"
    ]
  }
}

2. 使用chrome.identity.launchWebAuthFlow获取ID Token

getAuthToken默认返回Access Token,改用launchWebAuthFlow并指定response_type=id_token,直接获取ID Token:

const clientId = "你的Google OAuth客户端ID";
const redirectUri = chrome.identity.getRedirectURL();
// 生成随机nonce防止重放攻击
const nonce = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=id_token&scope=openid email profile&nonce=${nonce}`;

chrome.identity.launchWebAuthFlow(
  {
    url: authUrl,
    interactive: true
  },
  function(redirectUrl) {
    // 从回调URL的哈希参数中提取ID Token
    const idToken = new URL(redirectUrl).hash
      .slice(1)
      .split('&')
      .find(param => param.startsWith('id_token='))
      .split('=')[1];
    // 此时idToken可直接用于后端的tokeninfo验证
    console.log(idToken);
  }
);

补充说明

  • 需确保你的OAuth客户端ID已在Google Cloud Console中配置了Chrome扩展的重定向URI(即chrome.identity.getRedirectURL()返回的地址)。
  • nonce参数为可选但推荐项,用于提升安全性,避免重放攻击。

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 14:52:20