Cordova で OAuth プロバイダを使用して認証する

Firebase JS SDK では、Cordova 環境でサポートされている任意の OAuth プロバイダを使用して、Firebase ユーザーの認証が行えます。 サポートされている OAuth プロバイダを統合するには、Firebase SDK を使用してログインフローを実行するか、または OAuth フローを手動で行って、取得した OAuth 認証情報を Firebase に渡します。

Cordova の Firebase Authentication を設定する

  1. Firebase を JavaScript プロジェクトに追加します。Firebase スニペットを追加するときに、authDomain 構成変数をメモしてください。my-app.firebaseapp.com のようになります。Firebase でプロビジョニングされた firebaseapp.com ドメインの代わりにカスタム ドメインを使用する場合は、そのカスタム ドメインを使用する必要があります。

  2. Android アプリを設定する場合は、Android アプリを Firebase コンソールに追加し、アプリの詳細を入力します。生成された google-services.json は必要ありません。

  3. iOS アプリを設定する場合は、iOS アプリケーションを作成し、Firebase コンソールに追加します。後でカスタム URL スキームのプラグインをインストールするときに、iOS バンドル ID を追加する必要があります。

  4. Firebase Dynamic Links を有効にします。

    1. Firebase コンソールで [Dynamic Links] セクションを開きます。
    2. Dynamic Links の利用規約への同意と Dynamic Links のドメインの作成がまだの場合は、この時点でその作業を行います。

      Dynamic Links のドメインが作成済みである場合は、それをメモしておきます。Dynamic Links のドメインは、通常、次の例のようになります。

      example.page.link

      受信リンクをインターセプトするように Apple アプリまたは Android アプリを構成するときに、この値が必要になります。

  5. Firebase コンソールで Google ログインを有効にします。

    1. Firebase コンソールで [Authentication] セクションを開きます。
    2. [Sign-in method] タブで [Google] ログイン方法を有効にし、[保存] をクリックします。
  6. Cordova プロジェクトに必要なプラグインをインストールします。

    # Plugin to pass application build info (app name, ID, etc) to the OAuth widget.
    cordova plugin add cordova-plugin-buildinfo --save
    # Plugin to handle Universal Links (Android app link redirects)
    cordova plugin add cordova-universal-links-plugin-fix --save
    # Plugin to handle opening secure browser views on iOS/Android mobile devices
    cordova plugin add cordova-plugin-browsertab --save
    # Plugin to handle opening a browser view in older versions of iOS and Android
    cordova plugin add cordova-plugin-inappbrowser --save
    # Plugin to handle deep linking through Custom Scheme for iOS
    # Substitute *com.firebase.cordova* with the iOS bundle ID of your app.
    cordova plugin add cordova-plugin-customurlscheme --variable \
        URL_SCHEME=com.firebase.cordova --save
    
  7. 次の構成を Cordova の config.xml ファイルに追加します。ここで、AUTH_DOMAIN はステップ(1)のドメイン、DYNAMIC_LINK_DOMAIN はステップ(3c)のドメインです。

    <universal-links>
        <host name="DYNAMIC_LINK_DOMAIN" scheme="https" />
        <host name="AUTH_DOMAIN" scheme="https">
            <path url="/__/auth/callback"/>
        </host>
    </universal-links>
    

    構成例は次のようになります。

    <universal-links>
        <host name="example.page.link" scheme="https" />
        <host name="example-app.firebaseapp.com" scheme="https">
            <path url="/__/auth/callback"/>
        </host>
    </universal-links>
    

    カスタム ドメイン auth.custom.domain.com を使用する場合は、my-app.firebaseapp.com をこのドメインに置き換えます。

    Android アプリの場合、launchModesingleTask を使用します。

    <preference name="AndroidLaunchMode" value="singleTask" />
    

Firebase SDK を使用したログインフローの処理

  1. Firebase Auth は、現在の Cordova 環境を正しく判断するために deviceReady イベントに依存します。そのイベントがトリガーされた後、Firebase アプリのインスタンスが初期化されていることを確認します。

  2. Google プロバイダ オブジェクトのインスタンスを作成します。

    ウェブ モジュラー API

    import { GoogleAuthProvider } from "firebase/auth/cordova";
    
    const provider = new GoogleAuthProvider();

    名前空間が指定されたウェブ API

    var provider = new firebase.auth.GoogleAuthProvider();
  3. Google プロバイダ オブジェクトを使用して Firebase での認証を行うには、signInWithRedirect を使用します。signInWithPopup は Cordova ではサポートされていません。

    ウェブ モジュラー API

    import { getAuth, signInWithRedirect, getRedirectResult, GoogleAuthProvider } from "firebase/auth/cordova";
    
    const auth = getAuth();
    signInWithRedirect(auth, new GoogleAuthProvider())
      .then(() => {
        return getRedirectResult(auth);
      })
      .then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
    
        // This gives you a Google Access Token.
        // You can use it to access the Google API.
        const token = credential.accessToken;
    
        // The signed-in user info.
        const user = result.user;
        // ...
      }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
      });

    名前空間が指定されたウェブ API

    firebase.auth().signInWithRedirect(provider).then(() => {
      return firebase.auth().getRedirectResult();
    }).then((result) => {
      /** @type {firebase.auth.OAuthCredential} */
      var credential = result.credential;
    
      // This gives you a Google Access Token.
      // You can use it to access the Google API.
      var token = credential.accessToken;
      // The signed-in user info.
      var user = result.user;
      // ...
    }).catch((error) => {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
    });
  4. ログイン操作が完了する前にアプリのアクティビティが破棄されるケースを処理するには、アプリが読み込まれるときに getRedirectResult を呼び出します。

    ウェブ モジュラー API

    import { getAuth, getRedirectResult, GoogleAuthProvider } from "firebase/auth/cordova";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        if (credential) {        
          // This gives you a Google Access Token.
          // You can use it to access the Google API.
          const token = credential.accessToken;
          // The signed-in user info.
          const user = result.user;
          // ...
        }
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
      });

    名前空間が指定されたウェブ API

    firebase.auth().getRedirectResult().then((result) => {
      if (result.credential) {
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // This gives you a Google Access Token.
        // You can use it to access the Google API.
        var token = credential.accessToken;
        // The signed-in user info.
        var user = result.user;
        // ...
      }
    }).catch((error) => {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
    });

    同じメカニズムを使用して、linkWithRedirect を使用して新しいプロバイダをリンクするか、reauthenticateWithRedirect を使用して既存のプロバイダで再認証できます。