Search code examples
iosflutterfirebase-authenticationapple-sign-insign-in-with-apple

How to SILENTLY sign in with apple in flutter?


I have built an app in which the users can log in using Google, Email/Password, and Apple, using Firebase Auth.

For the Google Sign in, I get the credentials using

final GoogleSignInAccount? googleUser = await GoogleSignIn(clientId: clientId).signIn();
final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;
final oauthCredential = GoogleAuthProvider.credential(
      accessToken: googleAuth?.accessToken,
      idToken: googleAuth?.idToken,
    );
await FirebaseAuth.instance.signInWithCredential(oauthCredential);

And for the Apple Sign in, I use the sign_in_with_apple package as described here:

AuthorizationCredentialAppleID appleCredential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
        nonce: nonce,
      );
final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: appleCredential.identityToken,
        rawNonce: rawNonce,
      );
await FirebaseAuth.instance.signInWithCredential(oauthCredential);

This works fine so far for signing in the user after they confirm the login popup.

Now I want to add silent sign in (= sign in with the saved credentials without user interaction) to both Google an Apple. To do this I save the oAuthCredential after successfull login, and when the app is started the next time, I load it and call

await FirebaseAuth.instance.signInWithCredential(oAuthCredential);

to sign in the user. For Google this works perfectly fine, but on iOS for the Apple Sign In, I get this Firebase Auth error:

missing-or-invalid-nonce: Duplicate credential received. Please try again with a new credential.

I have googled for ages but haven't found anything helpful. What's the problem here?


Solution

  • As pointed out in this answer and the comment here by @Paulw11, FirebaseAuth.instance.currentUser magically all does this for me and I don't have to save any credentials at all.