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

Swift应用连接Firebase模拟器报错,如何修复JWT及Firestore流问题

修复Swift连接Firebase模拟器的JWT错误问题

你在开发Swift应用连接Firebase模拟器时,配置代码如下:

import SwiftUI
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseFirestore
import FirebaseFirestoreSwift
import FirebaseFunctions
import FirebaseFunctionsSwift

@main
struct HelloApp: App {
    
    init(){
        FirebaseApp.configure()
       
        //Auth
        Auth.auth().useEmulator(withHost:"localhost", port:9099)
        //Storage
        Storage.storage().useEmulator(withHost:"localhost", port:9199)
        //Firestore
        let settings = Firestore.firestore().settings
        settings.host = "localhost:8080"
        settings.isPersistenceEnabled = false
        settings.isSSLEnabled = false
        Firestore.firestore().settings = settings
        //Cloud Function
        Functions.functions().useEmulator(withHost: "http://localhost", port: 5001)
    }
    
    var body: some Scene {
        WindowGroup {
            MainContent()
        }
    }
}

运行时出现Firestore流错误:
[Firebase/Firestore][I-FST000001] WatchStream (14ed17248) Stream error: 'Unknown: An internal error has occurred, print and inspect the error details for more information.

日志显示核心问题:expected an unsecured JWT, the emulator does not validate JWTs and IS NOT SECURE

修复步骤:

  • 修正Cloud Functions模拟器的Host参数:原代码中Functions.functions().useEmulator的host带了http://前缀,这是错误的,应改为仅"localhost",方法内部会自动处理协议。
  • 简化Firestore模拟器配置:使用官方提供的useEmulator方法替代手动修改settings,该方法会自动配置正确的SSL和持久化参数,避免手动设置遗漏:
    Firestore.firestore().useEmulator(withHost: "localhost", port: 8080)
    
  • 确保Auth模拟器优先配置:在FirebaseApp.configure()后立即配置Auth模拟器,保证所有认证操作都走模拟器环境,避免使用生产环境的JWT。
  • 确认使用模拟器内认证账号:登录操作(如匿名登录、邮箱密码登录)需在模拟器启动后进行,确保生成的是模拟器认可的无签名JWT。

修改后的完整初始化代码:

init(){
    FirebaseApp.configure()
   
    // Auth 模拟器优先配置
    Auth.auth().useEmulator(withHost:"localhost", port:9099)
    // Firestore 模拟器(简化配置)
    Firestore.firestore().useEmulator(withHost: "localhost", port: 8080)
    // Storage 模拟器
    Storage.storage().useEmulator(withHost:"localhost", port:9199)
    // Cloud Functions 模拟器(修正Host)
    Functions.functions().useEmulator(withHost: "localhost", port: 5001)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:05:31