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

Google One Tap JS/HTML API在Safari中返回的JWT缺失nonce问题咨询

Google One Tap在Safari中JWT缺失nonce的替代解决方案

问题背景

使用Google One Tap的Javascript/HTML API集成时,已配置nonce参数,但在Safari 16.1版本中,登录返回的JWT里不包含该nonce;Chrome和Firefox则可正常返回。开启Safari默认的「阻止跨网站跟踪」时问题出现,关闭设置则恢复正常,且添加itp_support参数无改善。

集成代码示例:

const initializeGSI = () => {
    google.accounts.id.initialize({
      client_id: '132-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
      cancel_on_tap_outside: false,
      nonce: '7342364',
      callback: onOneTapSignedIn
    });
};

可行解决方案(无需修改用户Safari设置)

1. 改用授权码流程替代隐式流程

Google One Tap默认的隐式流程受Safari ITP(智能跟踪防护)限制,导致nonce丢失。改用授权码流程,通过后端中转令牌:

  • 初始化时添加ux_mode: 'redirect'和response_type: 'code'参数,让Google重定向到你的后端接口
  • 后端拿到授权码后,向Google令牌端点请求ID Token,此时nonce会被正确包含在返回的JWT中
  • 调整后的初始化代码示例:
const initializeGSI = () => {
    google.accounts.id.initialize({
      client_id: '132-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
      cancel_on_tap_outside: false,
      nonce: '7342364',
      ux_mode: 'redirect',
      response_type: 'code',
      redirect_uri: '/your-backend-auth-endpoint'
    });
};

2. 调用Safari Storage Access API申请跨域存储权限

在触发Google One Tap前,先调用Safari专属的Storage Access API,请求获取Google域名的存储权限,确保nonce能正常传递:

async function requestStorageAccess() {
  if ('requestStorageAccess' in document) {
    try {
      await document.requestStorageAccess();
      // 权限获取成功后初始化Google One Tap
      initializeGSI();
    } catch (err) {
      // 权限请求失败,降级为传统登录按钮
      renderGoogleLoginButton();
    }
  } else {
    // 不支持该API的浏览器直接初始化
    initializeGSI();
  }
}

// 需通过用户交互触发(比如点击登录按钮)
document.getElementById('login-btn').addEventListener('click', requestStorageAccess);

注意:该API必须由用户交互触发(如点击事件),无法在页面加载时自动调用,否则会被Safari拦截。

3. 降级为传统Google登录按钮

若上述方案不适用,可暂时切换为传统Google登录按钮,其认证流程受Safari ITP影响更小,nonce可正常被包含在JWT中:

<div class="g-signin2" data-onsuccess="onOneTapSignedIn" data-nonce="7342364"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:20:45