使用 OAuth 提供者和 Cordova 進行身份驗證

透過 Firebase JS SDK,您可以讓 Firebase 使用者在 Cordova 環境中使用任何受支援的 OAuth 提供者進行身份驗證。您可以透過使用 Firebase SDK 執行登入流程,或手動執行 OAuth 流程並將產生的 OAuth 憑證傳遞給 Firebase 來整合任何受支援的 OAuth 提供者。

為 Cordova 設定 Firebase 身份驗證

  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 動態連結:

    1. Firebase 控制台中,開啟動態連結部分。
    2. 如果您尚未接受動態連結條款並建立動態連結網域,請立即執行。

      如果您已經建立了動態連結網域,請記下它。動態連結網域通常類似於以下範例:

      example.page.link

      當您配置 Apple 或 Android 應用程式以攔截傳入連結時,您將需要此值。

  5. 在 Firebase 控制台中啟用 Google 登入:

    1. Firebase 控制台中,開啟「驗證」部分。
    2. 登入方法標籤上,啟用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 應用程式singleTask應該用於launchMode

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

使用 Firebase SDK 處理登入流程

  1. Firebase Auth 依賴deviceReady事件才能正確決定目前的 Cordova 環境。確保 Firebase 應用程式實例在該事件觸發後已初始化。

  2. 建立 Google 提供者物件的實例:

    Web modular API

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

    Web namespaced API

    var provider = new firebase.auth.GoogleAuthProvider();
  3. 使用signInWithRedirect使用 Google 提供者物件透過 Firebase 進行身份驗證。請注意,Cordova 不支援signInWithPopup

    Web modular 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;
      });

    Web namespaced 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. 若要處理應用程式 Activity 在登入作業完成之前被銷毀的情況,請在應用程式載入時呼叫getRedirectResult

    Web modular 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;
      });

    Web namespaced 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重新驗證現有的提供者。