web-dev-qa-db-fra.com

Cause de l'erreur lors de la configuration de la connexion avec Apple pour Firebase IOS13 Swift?

J'ai suivi https://firebase.google.com/docs/auth/ios/Apple et il mentionne l'erreur que je reçois concernant "l'envoi du nonce haché SHA256 sous forme de chaîne hexadécimale" mais il ne propose aucune aide pour le résoudre et mes recherches ne m'ont pas donné de solution qui fonctionne.

Mon extrait de code du contrôleur de vue est


        fileprivate var currentNonce: String?

        @objc @available(iOS 13, *)
        func startSignInWithAppleFlow() {
          let nonce = randomNonceString()
          currentNonce = nonce
          let appleIDProvider = ASAuthorizationAppleIDProvider()
          let request = appleIDProvider.createRequest()
          request.requestedScopes = [.fullName, .email]
          request.nonce = sha256(nonce)
            print(request.nonce)

          let authorizationController = ASAuthorizationController(authorizationRequests: [request])
          authorizationController.delegate = self
          authorizationController.presentationContextProvider = self
          authorizationController.performRequests()
        }
        @available(iOS 13, *)
        private func sha256(_ input: String) -> String {
          let inputData = Data(input.utf8)
          let hashedData = SHA256.hash(data: inputData)
          let hashString = hashedData.compactMap {
            return String(format: "%02x", $0)
          }.joined()
            print(hashString)
          return hashString
        }
    }
    @available(iOS 13.0, *)
    extension LoginViewController: ASAuthorizationControllerDelegate {

      func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.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 fetch identity token")
            return
          }
          guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
            print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
            return
          }
          // Initialize a Firebase credential.
            print(nonce)
            let credential = OAuthProvider.credential(withProviderID: "Apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

            print(credential)
          // Sign in with Firebase.
          Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
            if (error != nil) {
              // Error. If error.code == .MissingOrInvalidNonce, make sure
              // you're sending the SHA256-hashed nonce as a hex string with
              // your request to Apple.
                print(authResult)
                print(error!)
                print(error!.localizedDescription)
              return
            }
            // User is signed in to Firebase with Apple.
            // ...
          }
        }
      }

Cette section est différente des instructions sur la page Web car Xcode a donné une erreur


    let credential = OAuthProvider.credential(withProviderID: "Apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

Si j'imprime le nonce immédiatement avant


    let credential = OAuthProvider.credential(withProviderID: "Apple.com",
                                                      idToken: idTokenString,
                                                      accessToken: nonce)

Je reçois 2eNjrtagc024_pd3wfnt_PZ0N89GZ_b6_QJ3IZ_

la valeur response.nonce est cd402f047012a2d5c129382c56ef121b53a679c0a5c5e37433bcde2967225afe

Évidemment, ce ne sont pas les mêmes, mais je n'arrive pas à comprendre ce que je fais mal.

La sortie d'erreur complète est

Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x60000388a820 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
    code = 400;
    errors =     (
                {
            domain = global;
            message = "MISSING_OR_INVALID_NONCE : Nonce is missing in the request.";
            reason = invalid;
        }
    );
    message = "MISSING_OR_INVALID_NONCE : Nonce is missing in the request.";
}}}, FIRAuthErrorUserInfoNameKey=ERROR_INTERNAL_ERROR, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.}
An internal error has occurred, print and inspect the error details for more information.
6
ruraldev

Est-il possible que vous utilisiez la mauvaise méthode d'identification? SUR le documentation on dirait que celui qui prend le nonce est:

 let credential = OAuthProvider.credential( withProviderID: "Apple.com", IDToken: appleIdToken, rawNonce: rawNonce )

mais celui que vous utilisez ici prend un jeton d'accès, je ne sais pas si cela aide.

0
ethanrj