In this tutorial we’ll see how to add Apple Sign In to our Flutter apps from scratch.

Apple Sign In is a new authentication method that is available on iOS 13 and above.

It is very convenient, as your iOS users already have an Apple ID, and can use it to sign in with your app.

So just as you would offer Google Sign In on Android, it makes sense to offer Apple Sign In on iOS.

We will use the Apple Sign In Flutter plugin available on pub.dev.

Note: this plugin supports iOS only, and you can only use this on devices running iOS 13 and above.

Prerequisites

  • Xcode 11 installed
  • An Apple Developer Account
  • An iOS 13.x device or simulator, signed in with an Apple ID

Project Setup

After creating a new Flutter project, add the following dependencies to your pubspec.yaml file:

dependencies:
  firebase_auth: ^0.15.3
  apple_sign_in: ^0.1.0
  provider: ^4.0.1

Note: we will use Provider for dependency injection, but you can use something else if you prefer.

Next, we need add Firebase to our Flutter app. Follow this guide for how to do this:

After we have followed the required steps, the GoogleService-Info.plist file should be added to our Xcode project.

And while in Xcode 11, select the Signing & Capabilities tab, and add “Sign In With Apple” as a new Capability:

Adding Sign In With Apple capability

Once this is done, ensure to select a team on the Code Signing section:

Set Code Signing options

This will generate and configure an App ID in the “Certificates, Identifiers & Profiles” section of the Apple Developer portal. If you don’t do this, sign-in won’t work.

As a last step, we need to enable Apple Sign In in Firebase. This can be done under Authentication -> Sign-in method:

This completes the setup for Apple Sign In, and we can dive into the code.

Checking if Apple Sign In is available

Before we add the UI code, let’s write a simple class to check if Apple Sign In is available:

import 'package:apple_sign_in/apple_sign_in.dart';

class AppleSignInAvailable {
  AppleSignInAvailable(this.isAvailable);
  final bool isAvailable;

  static Future<AppleSignInAvailable> check() async {
    return AppleSignInAvailable(await AppleSignIn.isAvailable());
  }
}

Then, in our main.dart file, let’s modify the entry point:

void main() async {
  // Fix for: Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
  WidgetsFlutterBinding.ensureInitialized();
  final appleSignInAvailable = await AppleSignInAvailable.check();
  runApp(Provider<AppleSignInAvailable>.value(
    value: appleSignInAvailable,
    child: MyApp(),
  ));
}

The first line prevents an exception that occurs if we attempt to send messages across the platform channels before the binding is initialized.

Then, we check if Apple Sign In is available by using the class we just created.

And we use Provider to make this available as a value to all widgets in our app.

Note: this check is done upfront so that appleSignInAvailable is available synchronously to the entire widget tree. This avoids using a FutureBuilder in widgets that need to perform this check.

Adding the UI code

Instead of the default counter app, we want to show a Sign In Page with a button:

import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:apple_sign_in_firebase_flutter/apple_sign_in_available.dart';
import 'package:apple_sign_in_firebase_flutter/auth_service.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SignInPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appleSignInAvailable =
        Provider.of<AppleSignInAvailable>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text('Sign In'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(6.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [            
            if (appleSignInAvailable.isAvailable)
              AppleSignInButton(
                style: ButtonStyle.black, // style as needed
                type: ButtonType.signIn, // style as needed
                onPressed: () {},
              ),
          ],
        ),
      ),
    );
  }
}

Note: we use a collection-if to only show the AppleSignInButton if Apple Sign In is available. See this video for UI-as-code operators in Dart.

Back to our main.dart file, we can update our root widget to use the SignInPage:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Apple Sign In with Firebase',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: SignInPage(),
    );
  }
}

At this stage, we can run the app on an iOS 13 simulator and get the following:

Apple Sign In Button

Adding the authentication code

Here is the full authentication service that we will use to sign in with Apple (explained below):

import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';

class AuthService {
  final _firebaseAuth = FirebaseAuth.instance;

  Future<FirebaseUser> signInWithApple({List<Scope> scopes = const []}) async {
    // 1\. perform the sign-in request
    final result = await AppleSignIn.performRequests(
        [AppleIdRequest(requestedScopes: scopes)]);
    // 2\. check the result
    switch (result.status) {
      case AuthorizationStatus.authorized:
        final appleIdCredential = result.credential;
        final oAuthProvider = OAuthProvider(providerId: 'apple.com');
        final credential = oAuthProvider.getCredential(
          idToken: String.fromCharCodes(appleIdCredential.identityToken),
          accessToken:
              String.fromCharCodes(appleIdCredential.authorizationCode),
        );
        final authResult = await _firebaseAuth.signInWithCredential(credential);
        final firebaseUser = authResult.user;
        if (scopes.contains(Scope.fullName)) {
          final updateUser = UserUpdateInfo();
          updateUser.displayName =
              '${appleIdCredential.fullName.givenName} ${appleIdCredential.fullName.familyName}';
          await firebaseUser.updateProfile(updateUser);
        }
        return firebaseUser;
      case AuthorizationStatus.error:
        print(result.error.toString());
        throw PlatformException(
          code: 'ERROR_AUTHORIZATION_DENIED',
          message: result.error.toString(),
        );

      case AuthorizationStatus.cancelled:
        throw PlatformException(
          code: 'ERROR_ABORTED_BY_USER',
          message: 'Sign in aborted by user',
        );
    }
    return null;
  }
}

First, we pass a List<Scope> argument to our method. Scopes are the kinds of contact information that can be requested from the user (email and fullName).

Then, we make a call to AppleSignIn.performRequests and await for the result.

Finally, we parse the result with a switch statement. The three possible cases are authorized, error and cancelled.

Authorized

If the request was authorized, we create an OAuthProvider credential with the identityToken and authorizationCode we received.

We then pass this to _firebaseAuth.signInWithCredential(), and get an AuthResult that we can use to extract the FirebaseUser.

And if we requested the full name, we can update the profile information of the FirebaseUser object with the fullName from the Apple ID credential.

Error or Cancelled

If authentication failed or was cancelled by the user, we throw a PlatformException that can be handled by at the calling site.

Using the authentication code

Now that our auth service is ready, we can add it to our app via Provider like so:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Provider<AuthService>(
      create: (_) => AuthService(),
      child: MaterialApp(
        title: 'Apple Sign In with Firebase',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.indigo,
        ),
        home: SignInPage(),
      ),
    );
  }
}

Then, in our SignInPage, we can add a method to sign-in and handle any errors:

Future<void> _signInWithApple(BuildContext context) async {
  try {
    final authService = Provider.of<AuthService>(context, listen: false);
    final user = await authService.signInWithApple(
        requestEmail: true, requestFullName: true);
    print('uid: ${user.uid}');
  } catch (e) {
    // TODO: Show alert here
    print(e);
  }
}

Finally, we remember to call this on the callback of the AppleSignInButton:

AppleSignInButton(
  style: ButtonStyle.black,
  type: ButtonType.signIn,
  onPressed: () => _signInWithApple(context),
)

Testing things

Our implementation is complete, and we can run the app.

If we press the sign-in button and an Apple ID is not configured on our simulator or device, we will get the following:

Apple Sign In Settings prompt

After signing in with our Apple ID, we can try again, and we will get this:

After continuing, we are prompted to enter the password for our Apple ID (or use touch ID/face ID if enabled on the device). If we have requested full name and email access, the user will have a chance edit the name, and choose to share or hide the email:

After confirming this, the sign-in is complete and the app is authenticated with Firebase.

Note: if the sign-in screen is not dismissed after authenticating, it’s likely because you forgot to set the team in the code signing options in Xcode.

The next logical step is to move away from the SignInPage and show the home page instead. This can be done by adding a widget above the SignInPage, to decide which page to show depending on the onAuthStateChaged stream of FirebaseAuth.

Congratulations, you have now enabled Apple Sign In in your Flutter app! Your iOS users are grateful. 🙏

Full Source Code is here on GitHub.

Happy coding!

#firebase #flutter #mobile-app #dart #security

Apple Sign In with Flutter & Firebase Authentication
53.05 GEEK