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

iOS应用中Apple登录Supabase Authentication失败问题求助

解决iOS应用中Supabase Apple登录提示"Bad ID token"问题

问题背景

在iOS应用中集成Supabase Authentication的Apple登录时,已完成以下配置:

  • 创建bundle ID为co.xx.mobile的应用
  • 在Xcode签名与功能中添加"Sign with Apple"
  • 创建Services ID并配置Supabase域名https://xx.supabase.co和重定向URLhttps://xx.supabase.co/auth/v1/callback
  • 创建勾选"Sign in with Apple"的密钥
  • 使用secret_gen.rb脚本生成密钥

确认credential.authorizationCode和credential.identityToken均不为空,但调用登录接口时返回400错误:

flutter: ----------------FIREBASE CRASHLYTICS----------------
flutter: AuthException(message: Bad ID token, statusCode: 400)

相关代码:

Future<AuthResponse> _signInWithApple() async {
    final rawNonce = supabase.auth.generateRawNonce();
    final hashedNonce = sha256.convert(utf8.encode(rawNonce)).toString();
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
      nonce: hashedNonce,
    );
    final idToken = credential.identityToken!;
    if (idToken == null) {
      throw const AuthException('Could not find ID Token from generated credential.');
    }
    try {
      return supabase.auth.signInWithIdToken(
        provider: OAuthProvider.apple,
        idToken: idToken,
        nonce: rawNonce,
      );
    } catch (e) {
      throw AuthException(e.toString());
    }
  }

解决步骤

1. 修正Nonce的哈希处理逻辑

Supabase要求传递给Apple的nonce是base64 URL编码的SHA-256哈希值,而非原始十六进制字符串。当前代码直接传递十六进制哈希,导致token验证失败。

修改哈希处理代码:

import 'dart:convert';
import 'package:crypto/crypto.dart';

// ...

final rawNonce = supabase.auth.generateRawNonce();
// 将SHA-256哈希结果转为base64 URL编码,并移除末尾等号
final hashedNonce = base64UrlEncode(sha256.convert(utf8.encode(rawNonce)).bytes)
    .replaceAll('=', '');

2. 验证Supabase控制台的Apple配置

  • 进入Supabase控制台Authentication > Providers > Apple:
    • 确认Team ID与Apple Developer Account中一致(可在Membership页面查看)
    • Services ID需与Apple Developer中创建的完全匹配(如co.xx.mobile.auth)
    • Key ID为Apple密钥页面显示的ID
    • Private Key需是secret_gen.rb生成的完整内容,无多余空格或换行

3. 检查ID Token的合法性

  • 解码返回的identityToken(JWT格式):
    • 确认aud字段为你的Services ID,而非应用bundle ID
    • 确认nonce字段与生成的rawNonce完全匹配
    • 检查exp字段,确保token未过期

4. 确认iOS应用的Apple登录配置

  • 在Apple Developer Account中,确保bundle ID的"Sign with Apple"功能已启用,并关联正确的Services ID
  • 检查Xcode项目的签名配置,确认"Sign with Apple"权限已包含在 entitlements 文件中

5. 排除环境问题

  • 优先使用真机测试,模拟器可能存在Apple登录token异常
  • 确保使用正式Apple Developer账号签名,避免个人团队账号的限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:37:47