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

如何用expo-apple-authentication实现Firebase苹果认证?遇受众不匹配错误

解决Firebase苹果认证中ID Token受众不匹配问题

问题根源

错误提示里的host.exp.Exponent是Expo Go默认的Bundle ID,而Firebase预期的是你自己应用注册的Bundle ID,两者不匹配导致ID Token验证失败。

修复步骤

1. 配置Expo项目的自定义Bundle ID

在项目根目录的app.json中指定iOS的Bundle ID,确保和Firebase控制台里配置的一致:

{
  "expo": {
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourapp" // 替换成你的实际Bundle ID
    }
  }
}

2. 完善认证代码(补全Nonce逻辑+正确获取凭证)

原代码存在未定义变量和Nonce处理缺失的问题,以下是完整修正后的代码:

首先添加生成和哈希Nonce的工具函数:

// 生成随机Nonce
function generateRandomNonce(length = 32) {
  const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
  let nonce = '';
  while (nonce.length < length) {
    const randomIndex = Math.floor(Math.random() * charset.length);
    nonce += charset[randomIndex];
  }
  return nonce;
}

// SHA-256哈希Nonce(Apple要求传入哈希后的Nonce,Firebase需要原始Nonce验证)
async function sha256(message) {
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

然后修改认证流程:

import { getAuth, OAuthProvider, signInWithCredential } from "firebase/auth";
import * as AppleAuthentication from 'expo-apple-authentication';

const auth = getAuth();

async function signInWithApple() {
  try {
    // 生成Nonce并哈希
    const unhashedNonce = generateRandomNonce();
    const hashedNonce = await sha256(unhashedNonce);

    // 发起Apple认证请求,传入哈希后的Nonce
    const appleCredential = await AppleAuthentication.signInAsync({
      requestedScopes: [
        AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
        AppleAuthentication.AppleAuthenticationScope.EMAIL
      ],
      nonce: hashedNonce
    });

    // 从Apple返回的凭证中提取ID Token
    const appleIdToken = appleCredential.identityToken;
    if (!appleIdToken) {
      throw new Error('Apple认证未返回ID Token');
    }

    // 创建Firebase的Apple认证凭证
    const provider = new OAuthProvider('apple.com');
    const authCredential = provider.credential({
      idToken: appleIdToken,
      rawNonce: unhashedNonce // 传入原始未哈希的Nonce
    });

    // 完成Firebase登录
    const result = await signInWithCredential(auth, authCredential);
    console.log('登录成功,用户信息:', result.user);
    // 这里可以添加登录后的业务逻辑
  } catch (error) {
    console.error('登录失败:', error);
  }
}

// 调用登录函数
signInWithApple();

3. 验证Firebase与Apple开发者后台配置

  • 登录Firebase控制台,进入Authentication > Sign-in method > Apple,确保配置的Bundle ID和你Expo项目中的一致。
  • 登录Apple开发者后台,确认你的Bundle ID已开启Sign in with Apple功能,并且关联了Firebase提供的Service ID和重定向URL。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:57:35