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

Firebase Apple登录问题:nonce返回nil触发致命崩溃

Firebase Apple登录currentNonce为nil的问题排查

问题描述

我在实现Firebase Authentication的Apple登录功能时,已将currentNonce设置为randomNonceString方法生成的nonce,但handleSignInWithAppleCompletion执行成功后,因currentNonce为nil触发致命错误:

Fatal error: Invalid state: a login callback was received, but no login request was sent.

我检查过代码、调试控制台,也尝试按照Firebase文档修改请求创建逻辑,但问题依旧。

相关代码

import SwiftUI
import LocalAuthentication
import FirebaseAuth
import CryptoKit
import _AuthenticationServices_SwiftUI

final class SignInManager: ObservableObject {
    @Published var errorMessage = ""
    
    private var currentNonce: String?
    
    // 生成随机nonce
    private func randomNonceString(length: Int = 32) -> String {
        precondition(length > 0)
        let charset: [Character] =
        Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
        var result = ""
        var remainingLength = length
        
        while remainingLength > 0 {
            let randoms: [UInt8] = (0 ..< 16).map { _ in
                var random: UInt8 = 0
                let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
                if errorCode != errSecSuccess {
                    fatalError(
                        "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
                    )
                }
                return random
            }
            
            randoms.forEach { random in
                if remainingLength == 0 {
                    return
                }
                
                if random < charset.count {
                    result.append(charset[Int(random)])
                    remainingLength -= 1
                }
            }
        }
        
        return result
    }
    
    @available(iOS 13, *)
    private func sha256(_ input: String) -> String {
        let inputData = Data(input.utf8)
        let hashedData = SHA256.hash(data: inputData)
        let hashString = hashedData.compactMap {
            String(format: "%02x", $0)
        }.joined()
        
        return hashString
    }
}

extension SignInManager {
    func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) {
        request.requestedScopes = [.fullName, .email]
        let nonce = randomNonceString()
        currentNonce = nonce
        request.nonce = sha256(nonce)
    }
    
    func handleSignInWithAppleCompletion(_ result: Result<ASAuthorization, Error>) {
        if case .failure(let failure) = result {
            errorMessage = failure.localizedDescription
        }
        else if case .success(let success) = result {
            if let appleIDCredential = success.credential as? ASAuthorizationAppleIDCredential {
                guard let nonce = currentNonce else {
                    fatalError("Invalid state: a login callback was received, but no login request was sent.")
                }
                guard let appleIDToken = appleIDCredential.identityToken else {
                    print("Unable to fetdch identify token.")
                    return
                }
                guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
                    print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
                    return
                }
                
                let credential = OAuthProvider.credential(withProviderID: "apple.com",
                                                          idToken: idTokenString,
                                                          rawNonce: nonce)
                Task {
                    do {
                        let result = try await Auth.auth().signIn(with: credential)
                        await updateDisplayName(for: result.user, with: appleIDCredential)
                    }
                    catch {
                        print("Error authenticating: \(error.localizedDescription)")
                    }
                }
            }
        }
    }
}

更新尝试

我尝试按照Firebase文档创建请求,但无效果:

func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) {
      let nonce = randomNonceString()
      currentNonce = nonce
      let appleIDProvider = ASAuthorizationAppleIDProvider()
      let request = appleIDProvider.createRequest()
      request.requestedScopes = [.fullName, .email]
      request.nonce = sha256(nonce)
}

同时附上SignInButtonView代码:

import SwiftUI
import FirebaseAuth
import AuthenticationServices

struct SignInButtonView: View {
    @EnvironmentObject var signInManager: SignInManager
    @Environment(\.colorScheme) var colorScheme
    
    var body: some View {
        VStack {
            // MARK: - Sign In With Apple
            HStack {
                SignInWithAppleButton { request in
                    SignInManager().handleSignInWithAppleRequest(request)
                } onCompletion: { result in
                    SignInManager().handleSignInWithAppleCompletion(result)
                }
                .signInWithAppleButtonStyle(colorScheme == .light ? .black : .white)
                .frame(maxWidth: .infinity, maxHeight: 50)
                .cornerRadius(8)
            }
            .padding()
        }
        .frame(width: 400)
    }
}

struct SignInButtonView_Previews: PreviewProvider {
    static var previews: some View {
        SignInButtonView()
    }
}

问题根源与解决方案

核心问题

在SignInButtonView的SignInWithAppleButton回调中,你每次都新建了独立的SignInManager实例:

  • 请求回调里的SignInManager()会生成一个实例,并设置它的currentNonce
  • 完成回调里的SignInManager()是另一个全新实例,它的currentNonce从未被赋值,自然为nil

两个回调使用的不是同一个SignInManager实例,导致状态无法共享。

修复步骤

  1. 修改SignInButtonView的回调逻辑,使用已经通过@EnvironmentObject注入的共享实例:
SignInWithAppleButton { request in
    signInManager.handleSignInWithAppleRequest(request) // 使用环境中的共享实例
} onCompletion: { result in
    signInManager.handleSignInWithAppleCompletion(result) // 使用同一个实例
}
  1. 恢复正确的请求处理方法,你更新后的方法会覆盖传入的请求参数,导致设置的nonce无效:
func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) {
    request.requestedScopes = [.fullName, .email]
    let nonce = randomNonceString()
    currentNonce = nonce
    request.nonce = sha256(nonce)
}
  1. 确保全局注入实例,在App入口处将SignInManager注入到环境中:
@main
struct YourApp: App {
    @StateObject private var signInManager = SignInManager()
    
    var body: some Scene {
        WindowGroup {
            SignInButtonView()
                .environmentObject(signInManager)
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:35:32