Firebase使用Apple登录时返回invalid-credential,尽管Apple令牌有效(Flutter iOS)

移动开发 2026-07-09

我在iOS上用Flutter + Firebase Auth实现Apple登录。Apple返回了一个有效的令牌,但Firebase拒绝了它,错误如下:

firebase_auth/invalid-credential — Invalid OAuth response from apple.com

环境信息:

  • firebase_core:4.6.0
  • firebase_auth:6.3.0
  • sign_in_with_apple:7.0.1
  • Flutter(最新版稳定版)
  • iOS部署目标:16.0
  • 通过TestFlight在真机测试(非模拟器)

Flutter代码(auth_service.dart):

final rawNonce = _generateNonce();
final nonce = _sha256ofString(rawNonce);

final appleCredential = await SignInWithApple.getAppleIDCredential(
  scopes: [AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName],
  nonce: nonce,
);

final oauthCredential = OAuthProvider('apple.com').credential(
  idToken: appleCredential.identityToken,
  rawNonce: rawNonce,
);

return await _auth.signInWithCredential(oauthCredential);

Nonce生成:

String _generateNonce([int length = 32]) {
  const charset =
      '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
  final random = Random.secure();
  return List.generate(length, (_) => charset[random.nextInt(charset.length)])
      .join();
}

String _sha256ofString(String input) {
  final bytes = utf8.encode(input);
  final digest = sha256.convert(bytes);
  return digest.toString();
}

设备端验证 —— 令牌声明已解码并确认正确:

  • isshttps://appleid.apple.com
  • aud:与Bundle ID精确匹配
  • nonce:存在,已正确进行SHA-256哈希
  • exp:未过期
  • email_verified:true
  • nonce_supported:true

Apple Developer配置 —— 全部已验证正确:

  • App ID已启用Sign in with Apple,作为主App ID
  • Services ID配置了正确的Firebase返回URL(https://<project>.firebaseapp.com/__/auth/handler
  • 已注册具备SIWA能力的密钥,并与正确的主App ID相关联
  • 在Apple Developer的 Membership中确认了Team ID

我已尝试过的方案:

  • 从头删除并重新添加Firebase的 Apple提供者
  • 通过不同方法多次重新粘贴.p8密钥
  • 生成了一个全新的密钥并更新Firebase —— 错误仍然存在
  • 将bundle ID放在Services ID字段中(而不是Services ID)——无变化
  • GCP审核日志对 identitytoolkit 显示为0 条结果——无法看到服务器端的拒绝原因

同一项目中,电子邮件/密码登录工作正常。拒绝发生在Firebase Auth的服务器端——Apple一侧已确认正确。

是否有人遇到Firebase拒绝一个有效的Apple令牌并给出此错误的情况?是否存在控制台看不到的项目级配置错误?

欢迎给出线索!已经在此花费超过6 小时……先行致谢

解决方案

对于Google Sign-in,需要同时使用accessToken和 idToken。你缺少了accessToken。

在你的示例中,在这里添加
accessToken: appleCredential.authorizationCode
如下所示:

final oauthCredential = OAuthProvider('apple.com').credential(
  idToken: appleCredential.identityToken,
  rawNonce: rawNonce,
);
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章