Search code examples
flutterfirebase-authentication

Getting user´s info with Apple Sign In


I am trying to implement Apple Signin to my Flutter app.

I have used the FlutterFire proposed code for it.

  Future<UserCredential> signInWithApple() async {
    // To prevent replay attacks with the credential returned from Apple, we
    // include a nonce in the credential request. When signing in with
    // Firebase, the nonce in the id token returned by Apple, is expected to
    // match the sha256 hash of `rawNonce`.
    final rawNonce = generateNonce();
    final nonce = sha256ofString(rawNonce);

    // Request credential for the currently signed in Apple account.
    final appleCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
      nonce: nonce,
    );

    // Create an `OAuthCredential` from the credential returned by Apple.
    final oauthCredential = OAuthProvider("apple.com").credential(
      idToken: appleCredential.identityToken,
      rawNonce: rawNonce,
    );

    // Sign in the user with Firebase. If the nonce we generated earlier does
    // not match the nonce in `appleCredential.identityToken`, sign in will fail.
 


    return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
  }

Is there a way to get some of the user´s data, like email, name, profile image?

I would like to create a user account for my project using some of the apple user data.

When launching signInWithApple() I am getting the following dialog

enter image description here


Solution

  • After getAppleIDCredential and signInWithCredential are completed, and the user allowed to access the data you requested, these should be accessible from appleCredential. For example after this code is completed:

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

    You can get user data from appleCredential:

    appleCredential.familyName
    appleCredential.givenName
    appleCredential.email
    

    It is good idea to wrap this whole sign in logic into a try / catch block to be able to catch exceptions.