🍎

FlutterでAppleSignを実装する

2022/09/01に公開

意外と難しかったです!

FlutterでAppleSignInを実装したかったのですが、これでいいのかな〜と考えながら、作ってみたらできた様です。
アカウントを一回消して、また新規登録すると名前のところが、nullになってしまうのが気になりましたが、今回は勉強用のサンプルなので、あまり深く考えずに作ってみました。

こちらの公式ドキュメントを参考にしましたが、コードをそのままコピペしても使えないので、技術記事も参考にしながらやってみました。
どれが、いい方法なのかわからないですね。
https://firebase.flutter.dev/docs/auth/social
https://qiita.com/ninoko1995/items/51f9dd75b32522476342

今回使用したライブラリはこちらです。

ボタンのデザインが用意されているライブラリ。使うときは幅と高さの設定を忘れずに!
https://pub.dev/packages/sign_in_button
AppleSignInに必要なライブラリ
https://pub.dev/packages/sign_in_with_apple
firebaseに必要なライブラリ
https://pub.dev/packages/firebase_core
https://pub.dev/packages/firebase_auth

X-codeの設定が必要なのと、AppleDeveloperへの登録が必要です。
アカウントが既にあれば、こちらのページからログインするページへ行けるはずです。
https://developer.apple.com/jp/programs/

x-codeの設定はQittaの記事を参考にやっていましたが、UIが変わっていて、操作で躓きましたね。
x-codeのプロジェクトを開くときに、白と青のアイコンがあるのですが、両方iOSのバージョンを13に設定しないと実機でbuildできませんでしたね😅
ちなみに、実機でbuildするには、Appleのアカウントを持ってないと、できませんのでお忘れなく!
x-code側で、チームの設定なるものをするところで、自身のAppleのアカウントを設定すれば使えます。

AppleDeveloperの白い画面のホームページで、設定をしたときに、Sign in with Appleに、何故か最初にチェックがつけられませんでした?
編集を後で行うとチェックつけれました🤔

今回は、Firebase CLIは使っていなくて、GoogleService-Info.pilistを使用しています。
x-codeで、白いアイコンの方を開いてドキュメント通りの位置に配置してください。

スクリーンショット

FirebaseのコンソールでAppleSignInの設定をQiitaの記事通りにやれば上手くいきました。
正しく設定ができていれば、このようにユーザー登録ができました!

サンプルコード

AppleSignInを使うには、実機が必要で、シュミレーターではできない様です😇
ご自身のiPhoneで動作を確認してください。

pubspec.yaml

name: apple_auth_sample
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.17.3 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_core: ^1.21.1
  firebase_auth: ^3.7.0
  sign_in_with_apple: ^4.1.0
  flutter_signin_button: ^2.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

main.dart

import 'package:apple_auth_sample/next.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_list.dart';
import 'package:flutter_signin_button/button_view.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const AppleSignIn(),
    );
  }
}

class AppleSignIn extends StatefulWidget {
  const AppleSignIn({Key? key}) : super(key: key);

  
  State<AppleSignIn> createState() => _AppleSignInState();
}

class _AppleSignInState extends State<AppleSignIn> {
  // 公式のを参考に作ったユーザー登録の関数
  Future<UserCredential> signInWithApple() async {
    print('AppSignInを実行');

    final rawNonce = generateNonce();

    // 現在サインインしているAppleアカウントのクレデンシャルを要求する。
    final appleCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    print(appleCredential);
    // Apple から返されたクレデンシャルから `OAuthCredential` を作成します。
    final oauthCredential = OAuthProvider("apple.com").credential(
      idToken: appleCredential.identityToken,
      rawNonce: rawNonce,
    );
    print(appleCredential);
    // Firebaseでユーザーにサインインします。もし、先ほど生成したnonceが
    // が `appleCredential.identityToken` の nonce と一致しない場合、サインインに失敗します。
    return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
  }

  // 上のとほぼ一緒。登録とログインができる。
  Future<UserCredential> AppleSignIn() async {
    print('AppSignInを実行');
    // 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();

    // Request credential for the currently signed in Apple account.
    final appleCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    print(appleCredential);
    // Create an `OAuthCredential` from the credential returned by Apple.
    final oauthCredential = OAuthProvider("apple.com").credential(
      idToken: appleCredential.identityToken,
      rawNonce: rawNonce,
    );
    // ここに画面遷移をするコードを書く!
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => NextPage()));
    print(appleCredential);
    // 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);
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('AppleSignIn'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('新規登録用です。'),
              SizedBox(height: 20),
              Container(
                width: 200,
                height: 30,
                child: SignInButton(
                  Buttons.Apple,
                  onPressed: () async {
                    signInWithApple();
                  },
                ),
              ),
              SizedBox(height: 20),
              Text('ログイン用です。'),
              SizedBox(height: 20),
              Container(
                width: 200,
                height: 30,
                child: SignInButton(
                  Buttons.Apple,
                  onPressed: () async {
                    AppleSignIn();
                  },
                ),
              ),
            ],
          ),
        ));
  }
}

ログイン先のページ
next.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class NextPage extends StatelessWidget {
  const NextPage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    final _auth = FirebaseAuth.instance;

    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
              onPressed: () async {
                await _auth.signOut();
                Navigator.pop(context);
                print('SignOutしました');
              },
              icon: Icon(Icons.arrow_back))
        ],
        title: Text('ようこそ'),
      ),
      body: Text('AppleSignInしました!'),
    );
  }
}

最後に

公式ドキュメントをまず見ながら、作りましたが途中で躓いて、技術記事も参考に、このコードはいらないのでは、と思って省略して使いました。
最近は、SMSログインを使っていると、AppleがAppleSignInもつけないと審査を通してくれない情報を見かけて、焦って勉強しました。
メールアドレスとパスワードのログインだけだと、審査には、引っかかならい様ですが、Appleさん怖いですね😅
自分の会社の機能を使わないと、「審査で落とすぞ!」ということでしょうか...
最近は、退会機能も必須らしいです。まあ、当然か...

Flutter大学

Discussion