跳过内容

在 iOS 上使用 Supabase 进行 Google 登录

本指南将帮助您在 iOS 上将 Google Sign-In 与 Supabase 身份验证集成。假设您已经完成:

the

the

完整的实现可以在 示例应用的 supabaseAuthUtils.ts 文件中找到。 本指南解释了关键概念和如何使用它。

使用身份验证助手

标题:使用身份验证助手

authenticateWithGoogleSupabase 函数处理整个身份验证流程:

import { authenticateWithGoogleSupabase } from './supabaseAuthUtils';
const result = await authenticateWithGoogleSupabase();
if (result.success) {
console.log('Signed in:', result.user);
// Navigate to your authenticated area
} else {
console.error('Error:', result.error);
}

有关身份验证流程的详细说明,包括 nonce 生成、 JWT 验证和 Supabase 登录,请参见 General Setup 指南中的 How It Works 部分.

注意事项

重要注意事项

iOS令牌缓存和非法Nonce问题

iOS令牌缓存和Nonce问题

iOS非法Nonce缓存问题

在iOS上,Google Sign-In可以缓存令牌,这可能会导致nonce验证失败。该 validateJWTToken 功能检测到这一点并自动处理它:

  1. 自动检测:功能检查令牌中的nonce是否与预期 nonceDigest
  2. 自动重试:如果验证失败,它会自动从Google注销并尝试一次
  3. 错误处理: 如果重试也失败,会返回错误

为什么会这样: iOS Google Sign-In SDK 为性能考虑缓存了令牌。当缓存的令牌返回时,它可能是使用不同的 nonce(或无 nonce)生成的,从而导致不匹配。

解决方案: 实现会自动处理这个问题,通过登出并重试,强制 Google 生成一个带有正确 nonce 的新令牌。

手动工作绕过 (如果自动重试不起作用):

// Logout first to clear cached tokens
await SocialLogin.logout({ provider: 'google' });
// Then authenticate
const result = await authenticateWithGoogleSupabase();

这确保了使用正确 nonce 的令牌被获得。

要查看完整的 code 参考,请参见 在 General Setup 指南中的 Complete Code Reference 部分.

重要注意事项

重要说明

随机数处理

随机数处理

Capgo 的随机数实现遵循了 React Native Google Sign In 文档中的模式 转到 Supabase:

  • rawNonce Supabase 生成一个 signInWithIdToken()
  • 并与 rawNonce 从 Google Sign-In 中获取的 ID 令牌中的 nonceDigest (SHA-256 哈希,16 进制编码) 转到
  • nonceDigest 参数 nonce Google Sign-In API 中的参数

自动重试机制

自动重试机制

authenticateWithGoogleSupabase 函数包含一个 retry 参数:

  • 第一次调用(retry=false):如果验证失败,自动注销并重试一次
  • 重试调用(retry=true):如果验证失败再次,立即返回错误

这可以自动处理iOS令牌缓存问题。

故障排除

故障排除

如果认证失败:

  • 令牌不匹配: 检查控制台日志以获取详细信息。 如果问题持续存在,请先手动注销
  • 无效的受众: 确保在 Google Cloud Console 和 Supabase 中的 Google Client IDs 匹配(包括 iOS 和 Web 客户端 ID)
  • 令牌验证失败: 确保在初始化调用中使用 mode: 'online' 在 initialize 调用中使用
  • 获取 idTokenInfo.plist 配置
  • : 确保 Info.plist 中的 URL 方案和 GIDClientID 正确 example app code 示例应用 __CAPGO_KEEP_0__