expo + firebaseアプリにAppleサインインの実装(EXPO SDK53)

By taiyou

はじめに

Expo + firebase で管理しているアプリに Apple SignIn を実装してみました。
そのアプリ

情報を探ってみても ExpoSDK のバージョンが異なっていたりして、自分の環境だとうまくいかなかったので
同じような人に参考になれば幸いです。

完成形

このような形で firebase の Authentication にアカウントが追加されます。 sdk

事前準備

expo-apple-authentication をインストール

npx expo install expo-apple-authentication


app.jsonのpluginsにexpo-apple-authenticationを使うように記述

"plugins": [
      "expo-apple-authentication"
    ]



コード

一部こちらのコードを参考にさせていただいています。 Qiita

import * as AppleAuthentication from "expo-apple-authentication";
import * as Crypto from "expo-crypto";
import { OAuthProvider, signInWithCredential } from "firebase/auth";

function nonceGen(length: number) {
  let result = "";
  let characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

const useSignInContainer = () => {
  const signInWithApple = async () => {
    try {
      const nonce = nonceGen(32); // ランダム文字列(ノンス)を生成
      const digestedNonce = await Crypto.digestStringAsync(
        Crypto.CryptoDigestAlgorithm.SHA256,
        nonce
      ); // SHA256でノンスをハッシュ化
      const result = await AppleAuthentication.signInAsync({
        requestedScopes: [
          // ユーザー情報のスコープを設定(名前とメールアドレスのみ可)
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
        nonce: digestedNonce, // Apple側にはハッシュ化したノンスを渡す
      });
      console.log("Apple Sign In result: ", result);
      let provider = new OAuthProvider("apple.com");
      let credential = provider.credential({
        idToken: result.identityToken ?? undefined,
        rawNonce: nonce, // Firebase側には元のノンスを渡して検証させる
      });
      const firebaseResult = await signInWithCredential(auth, credential);
      pageReplace("/home/library");
      console.log("Firebase Auth result: ", firebaseResult);
    } catch (e) {
      console.error(e);
    }
  };

  return {
    signInWithApple,
  };
};


あとは、UI 側でsignInWithAppleを置だけです。



おわりに

その他の記事もぜひご覧ください!

個人制作アプリ
英語長文リーダー
倉庫番

お問い合わせ: hiromacha1116@icloud.com