使用 FirebaseUI 輕鬆將登入新增至您的 Web 應用

FirebaseUI是一個建立在 Firebase 驗證 SDK 之上的程式庫,它提供了可在您的應用程式中使用的嵌入式 UI 流。 FirebaseUI 具有以下優點:

  • 多個提供者- 電子郵件/密碼、電子郵件連結、電話身份驗證、Google、Facebook、Twitter 和 GitHub 登入的登入流程。
  • 帳戶連結- 跨身分提供者安全連結使用者帳戶的流程。
  • 自訂- 覆寫 FirebaseUI 的 CSS 樣式以滿足您的應用要求。此外,由於 FirebaseUI 是開源的,因此您可以分叉專案並根據您的需求進行自訂。
  • 一鍵註冊和自動登入- 與一鍵註冊自動集成,實現快速跨裝置登入。
  • 在地化 UI - 國際化,支援 40多種語言
  • 升級匿名用戶- 能夠透過登入/註冊升級匿名用戶。有關更多信息,請訪問升級匿名用戶部分

在你開始之前

  1. 將 Firebase 驗證新增至您的 Web 應用程序,確保您使用的是 v9 相容版(建議)或更舊的 SDK(請參閱上面的側邊欄)。

  2. 透過以下選項之一包含 FirebaseUI:

    1. CDN

      將以下腳本和 CSS 檔案包含在頁面的 <head> 標籤中,位於 Firebase 控制台的初始化程式碼區段下方:

      <script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script>
      <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
      
    2. npm 模組

      使用以下命令透過 npm 安裝 FirebaseUI 及其相依性:

      $ npm install firebaseui --save
      

      require在原始檔中包含以下模組:

      var firebase = require('firebase');
      var firebaseui = require('firebaseui');
      
    3. 鮑爾組件

      使用以下命令透過 Bower 安裝 FirebaseUI 及其相依性:

      $ bower install firebaseui --save
      

      如果您的 HTTP 伺服器提供bower_components/中的文件,請在 HTML 中包含所需的文件:

      <script src="bower_components/firebaseui/dist/firebaseui.js"></script>
      <link type="text/css" rel="stylesheet" href="bower_components/firebaseui/dist/firebaseui.css" />
      

初始化 FirebaseUI

導入SDK後,初始化Auth UI。

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

設定登入方法

在使用 Firebase 登入使用者之前,您必須啟用並設定您想要支援的登入方法。

電子郵件地址和密碼

  1. Firebase 控制台中,開啟「驗證」部分並啟用電子郵件和密碼驗證。

  2. 將電子郵件提供者 ID 新增至 FirebaseUI signInOptions清單中。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        firebase.auth.EmailAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  3. 選用EmailAuthProvider可以設定為要求使用者輸入顯示名稱(預設為true )。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          requireDisplayName: false
        }
      ]
    });
    
  1. Firebase 控制台中,開啟「驗證」部分。在登入方法標籤上,啟用電子郵件/密碼提供者。請注意,必須啟用電子郵件/密碼登入才能使用電子郵件連結登入。

  2. 在同一部分中,啟用電子郵件連結(無密碼登入)登入方法,然後按一下「儲存」

  3. 將電子郵件提供者 ID 以及電子郵件連結signInMethod新增至 FirebaseUI signInOptions清單中。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD
        }
      ],
      // Other config options...
    });
    
  4. 有條件地渲染登入 UI 時(與單頁應用程式相關),使用ui.isPendingRedirect()來偵測 URL 是否對應於透過電子郵件連結登錄,並且需要渲染 UI 才能完成登入。

    // Is there an email link sign-in?
    if (ui.isPendingRedirect()) {
      ui.start('#firebaseui-auth-container', uiConfig);
    }
    // This can also be done via:
    if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
      ui.start('#firebaseui-auth-container', uiConfig);
    }
    
  5. 選用:用於電子郵件連結登入的EmailAuthProvider可以配置為允許或阻止使用者完成跨裝置登入。

    可以定義可選的emailLinkSignIn回呼以傳回發送連結時使用的firebase.auth.ActionCodeSettings配置。這提供了指定如何處理連結、自訂動態連結、深層連結中的附加狀態等的能力。如果未提供,則使用目前 URL 並觸發僅 Web 流。

    FirebaseUI-web 中的電子郵件連結登入與FirebaseUI-AndroidFirebaseUI-iOS相容,其中從 FirebaseUI-Android 啟動流程的使用者可以開啟連結並使用 FirebaseUI-web 完成登入。對於相反的流也是如此。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
          signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD,
          // Allow the user the ability to complete sign-in cross device,
          // including the mobile apps specified in the ActionCodeSettings
          // object below.
          forceSameDevice: false,
          // Used to define the optional firebase.auth.ActionCodeSettings if
          // additional state needs to be passed along request and whether to open
          // the link in a mobile app if it is installed.
          emailLinkSignIn: function() {
            return {
              // Additional state showPromo=1234 can be retrieved from URL on
              // sign-in completion in signInSuccess callback by checking
              // window.location.href.
              url: 'https://www.example.com/completeSignIn?showPromo=1234',
              // Custom FDL domain.
              dynamicLinkDomain: 'example.page.link',
              // Always true for email link sign-in.
              handleCodeInApp: true,
              // Whether to handle link in iOS app if installed.
              iOS: {
                bundleId: 'com.example.ios'
              },
              // Whether to handle link in Android app if opened in an Android
              // device.
              android: {
                packageName: 'com.example.android',
                installApp: true,
                minimumVersion: '12'
              }
            };
          }
        }
      ]
    });
    

OAuth 提供者(Google、Facebook、Twitter 和 GitHub)

  1. Firebase 控制台中,開啟「驗證」部分並啟用指定的 OAuth 提供者登入。確保也指定了相應的 OAuth 用戶端 ID 和金鑰。

  2. 另外,在「驗證」部分中,請確保將呈現登入頁面的網域也加入到授權網域清單中。

  3. 將 OAuth 提供者 ID 新增至 FirebaseUI signInOptions清單中。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        // List of OAuth providers supported.
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        firebase.auth.TwitterAuthProvider.PROVIDER_ID,
        firebase.auth.GithubAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  4. 可選:若要指定自訂範圍或每個提供者的自訂 OAuth 參數,您可以傳遞物件而不僅僅是提供程式值:

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
          scopes: [
            'https://www.googleapis.com/auth/contacts.readonly'
          ],
          customParameters: {
            // Forces account selection even when one account
            // is available.
            prompt: 'select_account'
          }
        },
        {
          provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID,
          scopes: [
            'public_profile',
            'email',
            'user_likes',
            'user_friends'
          ],
          customParameters: {
            // Forces password re-entry.
            auth_type: 'reauthenticate'
          }
        },
        firebase.auth.TwitterAuthProvider.PROVIDER_ID, // Twitter does not support scopes.
        firebase.auth.EmailAuthProvider.PROVIDER_ID // Other providers don't need to be given as object.
      ]
    });
    

電話號碼

  1. Firebase 控制台中,開啟「驗證」部分並啟用電話號碼登入。

  2. 確保將呈現您的登入頁面的網域也加入到授權網域清單中。

  3. 將電話號碼提供者 ID 新增至 FirebaseUI signInOptions清單中。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        firebase.auth.PhoneAuthProvider.PROVIDER_ID
      ],
      // Other config options...
    });
    
  4. 選用:PhoneAuthProvider 可以使用自訂 reCAPTCHA 參數進行配置,無論 reCAPTCHA 可見或不可見(預設為正常)。有關更多詳細信息,請參閱reCAPTCHA API 文件

    也可以設定在電話號碼輸入中選擇的預設國家/地區。有關完整的代碼列表,請參閱支援的國家/地區代碼列表。如果未指定,輸入的電話號碼將預設為美國 (+1)。

    目前支援以下選項。

    ui.start('#firebaseui-auth-container', {
      signInOptions: [
        {
          provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
          recaptchaParameters: {
            type: 'image', // 'audio'
            size: 'normal', // 'invisible' or 'compact'
            badge: 'bottomleft' //' bottomright' or 'inline' applies to invisible.
          },
          defaultCountry: 'GB', // Set default country to the United Kingdom (+44).
          // For prefilling the national number, set defaultNationNumber.
          // This will only be observed if only phone Auth provider is used since
          // for multiple providers, the NASCAR screen will always render first
          // with a 'sign in with phone number' button.
          defaultNationalNumber: '1234567890',
          // You can also pass the full phone number string instead of the
          // 'defaultCountry' and 'defaultNationalNumber'. However, in this case,
          // the first country ID that matches the country code will be used to
          // populate the country selector. So for countries that share the same
          // country code, the selected country may not be the expected one.
          // In that case, pass the 'defaultCountry' instead to ensure the exact
          // country is selected. The 'defaultCountry' and 'defaultNationaNumber'
          // will always have higher priority than 'loginHint' which will be ignored
          // in their favor. In this case, the default country will be 'GB' even
          // though 'loginHint' specified the country code as '+1'.
          loginHint: '+11234567890'
        }
      ]
    });
    

登入

若要啟動 FirebaseUI 登入流程,請透過傳遞底層Auth實例來初始化 FirebaseUI 實例。

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());

定義將在其中呈現 FirebaseUI 登入小工具的 HTML 元素。

<!-- The surrounding HTML is left untouched by FirebaseUI.
     Your app may use that space for branding, controls and other customizations.-->
<h1>Welcome to My Awesome App</h1>
<div id="firebaseui-auth-container"></div>
<div id="loader">Loading...</div>

指定 FirebaseUI 配置(支援的提供者和 UI 自訂以及成功回呼等)。

var uiConfig = {
  callbacks: {
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // User successfully signed in.
      // Return type determines whether we continue the redirect automatically
      // or whether we leave that to developer to handle.
      return true;
    },
    uiShown: function() {
      // The widget is rendered.
      // Hide the loader.
      document.getElementById('loader').style.display = 'none';
    }
  },
  // Will use popup for IDP Providers sign-in flow instead of the default, redirect.
  signInFlow: 'popup',
  signInSuccessUrl: '<url-to-redirect-to-on-success>',
  signInOptions: [
    // Leave the lines as is for the providers you want to offer your users.
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.TwitterAuthProvider.PROVIDER_ID,
    firebase.auth.GithubAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
    firebase.auth.PhoneAuthProvider.PROVIDER_ID
  ],
  // Terms of service url.
  tosUrl: '<your-tos-url>',
  // Privacy policy url.
  privacyPolicyUrl: '<your-privacy-policy-url>'
};

最後渲染FirebaseUI Auth介面:

// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);

升級匿名用戶

啟用匿名用戶升級

當匿名用戶登入或註冊永久帳戶時,您希望確保用戶可以繼續他們在註冊之前所做的事情。為此,只需在配置登入 UI 時將autoUpgradeAnonymousUsers設為true (預設為停用此選項)。

處理匿名使用者升級合併衝突

在某些情況下,最初匿名登入的使用者會嘗試升級到現有 Firebase 使用者。由於現有用戶無法連結到另一個現有用戶,因此當發生上述情況時,FirebaseUI 將觸發signInFailure回調,並顯示錯誤代碼firebaseui/anonymous-upgrade-merge-conflict 。錯誤物件還將包含永久憑證。回呼中需要觸發永久憑證登錄,完成登入。在透過auth.signInWithCredential(error.credential)完成登入之前,您必須儲存匿名使用者的資料並刪除匿名使用者。然後,登入完成後,將資料複製回非匿名使用者。下面的範例說明了此流程的工作原理。

// Temp variable to hold the anonymous user data if needed.
var data = null;
// Hold a reference to the anonymous current user.
var anonymousUser = firebase.auth().currentUser;
ui.start('#firebaseui-auth-container', {
  // Whether to upgrade anonymous users should be explicitly provided.
  // The user must already be signed in anonymously before FirebaseUI is
  // rendered.
  autoUpgradeAnonymousUsers: true,
  signInSuccessUrl: '<url-to-redirect-to-on-success>',
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
    firebase.auth.PhoneAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    // signInFailure callback must be provided to handle merge conflicts which
    // occur when an existing credential is linked to an anonymous user.
    signInFailure: function(error) {
      // For merge conflicts, the error.code will be
      // 'firebaseui/anonymous-upgrade-merge-conflict'.
      if (error.code != 'firebaseui/anonymous-upgrade-merge-conflict') {
        return Promise.resolve();
      }
      // The credential the user tried to sign in with.
      var cred = error.credential;
      // Copy data from anonymous user to permanent user and delete anonymous
      // user.
      // ...
      // Finish sign-in after data is copied.
      return firebase.auth().signInWithCredential(cred);
    }
  }
});

下一步

  • 有關使用和自訂 FirebaseUI 的更多信息,請訪問README
  • 如果您在 FirebaseUI 中發現問題並想要回報該問題,請使用GitHub 問題追蹤器