@16patsle/termlist-auth-ui 中文文档教程

发布于 5年前 浏览 25 项目主页 更新于 3年前

termlist-auth-ui , FirebaseUI 的 Web 分支 — Auth​。

FirebaseUI 是一个用于 Web 的开源 JavaScript 库,它提供了简单、 基于 Firebase SDK 的可自定义 UI 绑定 消除样板代码并推广最佳实践。

FirebaseUI Auth 提供了一个插入式身份验证解决方案,用于处理 UI 流 使用电子邮件地址和密码、电话号码、身份登录用户 提供商登录,包括 Google、Facebook、GitHub、Twitter、Apple、Microsoft、 Yahoo、OpenID Connect (OIDC) 提供商和 SAML 提供商。 它建立在 Firebase 身份验证

FirebaseUI 组件实现了移动设备身份验证的最佳实践 设备和网站,帮助您的应用程序进行登录和注册转换。 它 还可以处理帐户恢复和帐户链接等情况 安全敏感且容易出错的处理。

FirebaseUI Auth 客户端也可用于 iOSAndroid

FirebaseUI 完全支持所有最新的浏览器。 使用联合身份登录 提供商(Google、Facebook、Twitter、GitHub、Apple、Microsoft、Yahoo、OIDC、 SAML) 在 Cordova/Ionic 环境中也受支持。 额外的非浏览器 环境(React Native ...)或 Chrome 扩展将在 底层 Firebase 核心 SDK 以兼容的方式支持它们 火力地堡用户界面。

Table of Contents

  1. Demo
  2. Installation
  3. Usage instructions
  4. Configuration
  5. Customization
  6. Advanced
  7. Developer Setup
  8. IAP External Identities Support with FirebaseUI
  9. Cordova Setup
  10. React DOM Setup
  11. Angular Setup
  12. Known issues
  13. Release Notes

Demo

可在此处访问: https://fir-ui-demo-84a6c.firebaseapp.com

Installation

Option 1: CDN

您只需要在 标签中包含以下脚本和 CSS 文件 您的页面,在 Firebase 控制台的初始化片段下方:

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

Localized Widget

小部件的本地化版本可通过 CDN 获得。 要使用本地化的小部件,请加载 本地化的 JS 库而不是默认库:

<script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth__{LANGUAGE_CODE}.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />

其中 {LANGUAGE_CODE} 替换为您想要的语言的代码。 例如,法国人 该库的版本可在 <代码>https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth__fr.js。 可用列表 语言及其各自的语言代码可以在 LANGUAGES.md 中找到。

从右到左的语言也需要从右到左版本的样式表,可在 https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth-rtl.css ,而不是默认的 样式表。 支持的从右到左的语言是阿拉伯语 (ar)、波斯语 (fa) 和希伯来语 (iw)。

Option 2: npm Module

使用以下命令通过 npm 安装 FirebaseUI 及其对等依赖项 Firebase 命令:

$ npm install firebase --save
$ npm install firebaseui --save

然后您可以在源文件中 require 以下模块:

var firebase = require('firebase');
var firebaseui = require('firebaseui');
// or using ES6 imports:
import * as firebaseui from 'firebaseui'

或者如果您的 HTTP 服务器提供这些文件,则在 HTML 中包含所需的文件 在 node_modules/ 中:

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

Option 3: Bower component

以下命令通过 Bower 安装 FirebaseUI 及其依赖

$ bower install firebaseui --save

使用 项: bower_components/ 中的文件:

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

Using FirebaseUI for Authentication

FirebaseUI 包括以下流程:

  1. Interaction with Identity Providers such as Google and Facebook
  2. Phone number based authentication
  3. Sign-up and sign-in with email accounts (email/password and email link)
  4. Password reset
  5. Prevention of account duplication (activated when "One account per email address" setting is enabled in the Firebase console . This setting is enabled by default.)
  6. Account Chooser for remembering emails
  7. Integration with one-tap sign-up
  8. Ability to upgrade anonymous users through sign-in/sign-up
  9. Sign-in as a guest

Configuring sign-in providers

要使用 FirebaseUI 对用户进行身份验证,您首先需要配置每个 您想要在他们自己的开发者应用程序设置中使用的提供商。 请阅读 Firebase 身份验证的开始之前部分位于以下链接:

Google Cloud 的身份平台 (GCIP) 开发人员,您还可以启用 SAML 和 OIDC 提供商 说明:

Starting the sign-in flow

您首先需要初始化您的 Firebase 应用 。 这 firebase.auth.Auth 实例应该传递给构造函数 <代码>firebaseui.auth.AuthUI。 然后,您可以使用 CSS 调用 start 方法 决定在哪里创建小部件的选择器,以及一个配置对象。

以下示例显示了如何使用所有受支持的设置登录屏幕 提供商。 请参考 示例文件夹中的演示应用程序 有关更深入的示例,展示单页应用程序模式。

直接从文件执行时,Firebase 和 FirebaseUI 不起作用(即 在浏览器中打开文件,而不是通过网络服务器)。 始终运行 firebase serve (或您首选的本地服务器)在本地测试您的应用。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />
    <script type="text/javascript">
      // FirebaseUI config.
      var uiConfig = {
        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,
          firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
        ],
        // tosUrl and privacyPolicyUrl accept either url string or a callback
        // function.
        // Terms of service url/callback.
        tosUrl: '<your-tos-url>',
        // Privacy policy url/callback.
        privacyPolicyUrl: function() {
          window.location.assign('<your-privacy-policy-url>');
        }
      };

      // Initialize the FirebaseUI Widget using Firebase.
      var ui = new firebaseui.auth.AuthUI(firebase.auth());
      // The start method will wait until the DOM is loaded.
      ui.start('#firebaseui-auth-container', uiConfig);
    </script>
  </head>
  <body>
    <!-- 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></div>
  </body>
</html>

这仅与单页应用程序或有条件地呈现登录 UI(例如按钮点击)的应用程序相关

从 accountchooser.com 重定向回来时,身份提供商(如 Google) 和 Facebook 或电子邮件链接登录,需要调用 start() 方法 完成登录流程。 如果需要用户交互来启动初始登录过程,您需要 检查页面加载时是否有挂起的重定向操作,以检查是否 start() 需要被调用。

要检查是否有挂起的重定向操作来完成登录尝试, 在决定是否渲染 FirebaseUI 之前检查 isPendingRedirect() 通过 start()

if (ui.isPendingRedirect()) {
  ui.start('#firebaseui-auth-container', uiConfig);
}

以下是您将如何跟踪所有页面的 Auth 状态:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script type="text/javascript">
      initApp = function() {
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var uid = user.uid;
            var phoneNumber = user.phoneNumber;
            var providerData = user.providerData;
            user.getIdToken().then(function(accessToken) {
              document.getElementById('sign-in-status').textContent = 'Signed in';
              document.getElementById('sign-in').textContent = 'Sign out';
              document.getElementById('account-details').textContent = JSON.stringify({
                displayName: displayName,
                email: email,
                emailVerified: emailVerified,
                phoneNumber: phoneNumber,
                photoURL: photoURL,
                uid: uid,
                accessToken: accessToken,
                providerData: providerData
              }, null, '  ');
            });
          } else {
            // User is signed out.
            document.getElementById('sign-in-status').textContent = 'Signed out';
            document.getElementById('sign-in').textContent = 'Sign in';
            document.getElementById('account-details').textContent = 'null';
          }
        }, function(error) {
          console.log(error);
        });
      };

      window.addEventListener('load', function() {
        initApp();
      });
    </script>
  </head>
  <body>
    <h1>Welcome to My Awesome App</h1>
    <div></div>
    <div></div>
    <pre></pre>
  </body>
</html>

Configuration

FirebaseUI 支持以下配置参数。

NameRequiredDescription
autoUpgradeAnonymousUsersNoWhether to automatically upgrade existing anonymous users on sign-in/sign-up. See Upgrading anonymous users .
Default: false When set to true , signInFailure callback is required to be provided to handle merge conflicts.
callbacksNoAn object of developers callbacks after specific events.
Default: {}
credentialHelperNoThe Credential Helper to use. See Credential Helper .
Default: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM
queryParameterForSignInSuccessUrlNoThe redirect URL parameter name for the sign-in success URL. See Overwriting the sign-in success URL .
Default: "signInSuccessUrl"
queryParameterForWidgetModeNoThe redirect URL parameter name for the “mode” of the Widget. See FirebaseUI widget modes .
Default: "mode"
signInFlowNoThe sign-in flow to use for IDP providers: redirect or popup .
Default: "redirect"
immediateFederatedRedirectNoA boolean which determines whether to immediately redirect to the provider's site or instead show the default 'Sign in with Provider' button when there is only a single federated provider in signInOptions . In order for this option to take effect, the signInOptions must only hold a single federated provider (like 'google.com') and signInFlow must be set to 'redirect'.
signInOptionsYesThe list of providers enabled for signing into your app. The order you specify them will be the order they are displayed on the sign-in provider selection screen.
signInSuccessUrlNoThe URL where to redirect the user after a successful sign-in. Required when the signInSuccessWithAuthResult callback is not used or when it returns true .
tosUrlYesThe URL of the Terms of Service page or a callback function to be invoked when Terms of Service link is clicked.
privacyPolicyUrlYesThe URL of the Privacy Policy page or a callback function to be invoked when Privacy Policy link is clicked.

Credential Helper

凭据助手的作用是帮助您的用户登录您的网站。 启用后,系统会提示您的用户提供电子邮件地址和 他们从您的应用程序或其他应用程序中保存的用户名。 FirebaseUI 支持以下凭证助手:

accountchooser.com

accountchooser.com 是 启用(默认启用),登录时或 使用电子邮件注册,用户将被重定向到 accountchooser.com 网站并将能够选择他们保存的帐户之一。 你可以 通过指定以下值来禁用它。 此功能始终禁用 非 HTTP/HTTPS 环境。

One-tap sign-up

注意:此 API 的 Beta 测试程序目前已关闭。

一键注册 提供无缝身份验证流程 您的用户使用 Google 的一键注册和自动登录 API。 通过一键注册,系统会提示用户创建一个带有对话框的帐户 这与 FirebaseUI NASCAR 屏幕一致。 只需轻按一下,他们就会得到一个 使用您的服务的安全、基于令牌、无密码的帐户,受他们的保护 谷歌帐户。 由于这个过程是无摩擦的,用户更有可能 登记。 返回的用户会自动登录,即使他们切换设备或 平台,或者在他们的会话到期之后。 一键注册与 FirebaseUI 集成,如果您请求 Google OAuth 范围,您仍然会取回预期的 Google OAuth 访问令牌,即使 用户通过一次点击流程。 但是,在那种情况下,“重定向”流程是 即使在指定 'popup' 时也始终使用。 此外,如果您选择强制提示 Google 登录,一键自动 登录将被自动禁用。 一键式是一项附加功能,仅在最新的常绿版本中受支持 现代浏览器环境。 有关如何配置一键式注册的更多信息,请参阅 一键式入门指南

以下示例展示了如何使用 FirebaseUI 配置一键式注册。 以及相应的一键式 credentialHelperclientIdauthMethod 必须由 Firebase Google 提供商提供:

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      // Google provider must be enabled in Firebase Console to support one-tap
      // sign-up.
      provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      // Required to enable this provider in one-tap sign-up.
      authMethod: 'https://accounts.google.com',
      // Required to enable ID token credentials for this provider.
      // This can be obtained from the Credentials page of the Google APIs
      // console.
      clientId: 'xxxxxxxxxxxxxxxxx.apps.googleusercontent.com'
    },
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.TwitterAuthProvider.PROVIDER_ID,
    firebase.auth.GithubAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
  ],
  // Required to enable one-tap sign-up credential helper.
  credentialHelper: firebaseui.auth.CredentialHelper.GOOGLE_YOLO
});
// Auto sign-in for returning users is enabled by default except when prompt is
// not 'none' in the Google provider custom parameters. To manually disable:
ui.disableAutoSignIn();

可以通过调用禁用返回用户的自动登录 <代码>ui.disableAutoSignIn()。 如果 FirebaseUI 登录页面是 在用户注销后呈现。

要通过一键注册查看 FirebaseUI 的运行情况,请查看 FirebaseUI 演示应用

Credential HelperValue
accountchooser.comfirebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM
One-tap sign-upfirebaseui.auth.CredentialHelper.GOOGLE_YOLO
None (disable)firebaseui.auth.CredentialHelper.NONE

Available providers

ProviderValue
Googlefirebase.auth.GoogleAuthProvider.PROVIDER_ID
Facebookfirebase.auth.FacebookAuthProvider.PROVIDER_ID
Twitterfirebase.auth.TwitterAuthProvider.PROVIDER_ID
Githubfirebase.auth.GithubAuthProvider.PROVIDER_ID
Email and passwordfirebase.auth.EmailAuthProvider.PROVIDER_ID
Phone numberfirebase.auth.PhoneAuthProvider.PROVIDER_ID
Anonymousfirebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
Appleapple.com
Microsoftmicrosoft.com
Yahooyahoo.com
SAML (GCIP only)saml.*********
OIDC (GCIP only)oidc.*********

Configure OAuth providers

要为每个提供商指定自定义范围或自定义 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.
  ]
});

Generic OAuth provider

您可以让您的用户使用 OAuth 提供者通过 FirebaseUI 进行身份验证,例如 苹果Microsoft Azure Active Directory雅虎 通过将通用 OAuth 登录集成到您的应用程序中。

您只需要在 signInOptions 中传递提供者 ID,FirebaseUI 提供 登录按钮的默认配置(按钮颜色、图标和显示名称):

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    'apple.com',
    'microsoft.com',
    'yahoo.com',
  ]
});

您还可以使用自己的自定义配置覆盖这些默认配置。 通用 OAuth 提供者的 signInOptions 支持以下配置 参数。

NameRequiredDescription
providerYesThe provider ID, eg. microsoft.com .
providerNameNoThe provider name displayed to end users (sign in button/linking prompt), eg. "Microsoft" Default: provider ID
buttonColorNoThe color of sign in button. The css of the button can be overwritten with the attribute/value in the HTML element: data-provider-id="providerId"
iconUrlNoThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
scopesNoThe list of additional OAuth 2.0 scopes beyond basic profile that you want to request from the authentication provider.
customParametersNoThe list of additional custom OAuth parameters that you want to send with the OAuth request.
loginHintKeyNoThe key of the custom parameter, with which the login hint can be passed to the provider. This is useful in case a user previously signs up with an IdP like Microsoft and then tries to sign in with email using the same Microsoft email. FirebaseUI can then ask the user to sign in with that email to the already registered account with Microsoft. For Microsoft and Yahoo, this field is `login_hint`.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'microsoft.com',
      providerName: 'Microsoft',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>',
      loginHintKey: 'login_hint',
      scopes: [
        'mail.read'
      ],
      customParameters: {
        prompt: 'consent'
      }
    }
  ]
});

OpenID Connect (OIDC) providers (GCIP only)

对于 GCIP 客户,您可以为应用启用 OpenID 连接 (OIDC) 使用 FirebaseUI 进行身份验证。

OIDC 提供商的 signInOptions 支持以下配置参数。

NameRequiredDescription
providerYesThe provider ID, eg. oidc.myProvider .
providerNameNoThe provider name displayed to end users (sign in button/linking prompt). Default: provider ID
buttonColorYesThe color of sign in button. The css of the button can be overwritten with attribute/value in the HTML element: data-provider-id="providerId"
iconUrlYesThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
customParametersNoThe list of additional custom parameters that the OIDC provider supports.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'oidc.myProvider`,
      providerName: 'MyOIDCProvider',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>',
      customParameters: {
        OIDCSupportedParameter: 'value'
      }
    }
  ]
});

SAML providers (GCIP only)

对于 GCIP 客户,您可以为应用启用 SAML 使用 FirebaseUI 进行身份验证。

SAML 提供商的 signInOptions 支持以下配置参数。

NameRequiredDescription
providerYesThe provider ID, eg. saml.myProvider .
providerNameNoThe provider name displayed to end users (sign in button/linking prompt). Default: provider ID
buttonColorYesThe color of sign in button. The css of the button can be overwritten with attribute/value in the HTML element: data-provider-id="providerId"
iconUrlYesThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'saml.myProvider',
      providerName: 'MySAMLProvider',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>'
    }
  ]
});

Configure Email Provider

您可以通过 FirebaseUI 配置电子邮件/密码或电子邮件/链接登录 在配置 signInOptions 中提供相关对象 大批。

NameTypeRequiredDescription
providerstringYesFor email sign-in, this should be firebase.auth.EmailAuthProvider.PROVIDER_ID .
requireDisplayNamebooleanNoDefines whether to require the user to provide a display name during email and password sign up.
Default: true
signInMethodstringNoDefines whether to use email and password or email link authentication. This should be firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD for email and password sign-in, firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD for email link authentication.
Default: firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD
forceSameDevicebooleanNoWhether to force same device flow. If false, opening the link on a different device will display a message instructing the user to open the link on the same device or browser. This should be true when used with anonymous user upgrade flows. This is only relevant to email link sign-in. Default: false
emailLinkSignInfunctionNoDefines the optional callback function to return firebase.auth.ActionCodeSettings configuration to use when sending the link. This provides the ability to specify how the link can be handled, custom dynamic link, additional state in the deep link, etc. When not provided, the current URL is used and a web only flow is triggered. This is only relevant to email link sign-in.

Email and Password

电子邮件和密码身份验证是电子邮件的默认登录方法 提供商。 带有电子邮件和密码的 EmailAuthProvider 可以配置为要求 用户输入显示名称(默认为 true )。

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      requireDisplayName: false
    }
  ]
});

Email Link Authentication

FirebaseUI 支持使用电子邮件链接登录和注册。 通过 FirebaseUI 使用电子邮件链接登录具有以下优势:

  • End to end support for email link sign-in with only a few configuration lines.
  • Enforces security and privacy best practices.
  • Ability to force same device flows or allow cross device flows where a user can start the flow on one device and end it on another. This also covers Android and iOS where email link sign-in is also supported with FirebaseUI-android and FirebaseUI-ios .
  • Ability to switch to email link sign-in while continuing to sign-in existing users with email and password.
  • Ability to support account linking, where an existing email link user signing in with Facebook for the first time using the same email will have both accounts merged so they can sign in with either (Facebook or email link) going forward.
  • Ability to support anonymous user upgrade as long as the flow starts and ends on the same device. Users opening the link on a different device will be notified to open the link on the same device where the flow started.

下面的示例代码演示了如何配置电子邮件链接登录 火力地堡用户界面。 在此示例中,允许跨设备流和附加状态 在 URL 中传递,以及配置链接以通过以下方式打开的能力 移动应用程序也是如此。

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      // Use email link authentication and do not require password.
      // Note this setting affects new users only.
      // For pre-existing users, they will still be prompted to provide their
      // passwords on sign-in.
      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'
          }
        };
      }
    }
  ]
});

有条件地呈现登录 UI 时(与单页应用程序相关), 使用 ui.isPendingRedirect() 检测 URL 是否对应于登录 电子邮件链接,需要呈现 UI 才能完成登录。 你也可以只使用 firebase.auth().isSignInWithEmailLink(window.location.href)

// 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);
}

可以在登录时检索在 url 中传递的其他状态 通过 signInSuccess 回调完成。

// ...
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
  // If a user signed in with email link, ?showPromo=1234 can be obtained from
  // window.location.href.
  // ...
  return false;
}

FirebaseUI 使用 历史 API 到 从与电子邮件链接登录相关的查询参数中清除 URL 处理一次性代码。 这可以防止用户重新触发 页面重新加载时或用户注销并尝试时再次登录完成流程 在单页应用程序中再次登录等。

当不强制执行相同的设备流程时,用户将通过帐户链接 流程(例如,用户使用属于某个电子邮件的电子邮件登录 Facebook 现有的电子邮件链接用户)将在不同的设备上打开链接 选择继续使用电子邮件链接登录而不合并 Facebook 凭据或指示在流所在的同一设备上打开链接 启动以成功合并两个帐户。

您不能同时使用电子邮件/密码和电子邮件/链接登录。 只有一个 模式可以一次配置。 但是,如果您之前注册过用户 与密码。 切换到电子邮件/链接将仅适用于新用户和 现有密码用户将继续在登录时收到输入密码的提示。

Configure Phone Provider

PhoneAuthProvider 可以配置自定义 reCAPTCHA 参数 reCAPTCHA 是可见还是不可见(默认为 normal )。 请参阅 reCAPTCHA API 文档 更多细节。

也可以设置在电话号码输入中选择的默认国家/地区。 支持的国家/地区代码列表 。 如果未指定, 电话号码输入将默认为美国 (+1)。

要选择的国家也可以配置为 blacklistedCountries 或 <代码>列入白名单的国家/地区。 它接受 ISO (alpha-2) 或 E164(前缀为“+”) 格式化的国家代码。 无效的国家代码将被忽略。 whitelistedCountriesblacklistedCountries 不能同时指定。

当前支持以下选项。 任何其他 参数将被忽略。

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',
      // You can provide a 'whitelistedCountries' or 'blacklistedCountries' for
      // countries to select. It takes an array of either ISO (alpha-2) or
      // E164 (prefix with '+') formatted country codes. If 'defaultCountry' is
      // not whitelisted or is blacklisted, the default country will be set to the
      // first country available (alphabetical order). Notice that
      // 'whitelistedCountries' and 'blacklistedCountries' cannot be specified
      // at the same time.
      whitelistedCountries: ['US', '+44']
    }
  ]
});

Configure Anonymous Provider

可以启用 AnonymousAuthProvider 让用户继续作为访客。 如果 用户已经匿名登录,单击此登录选项将保留 相同的当前匿名用户。 另外,匿名自动升级时 除此选项外还启用了用户并且用户已经登录 匿名,单击此登录选项也将保持相同的当前状态 匿名用户。

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
    }
  ]
});

Sign In Flows

有两个登录流程可用:

  • redirect , the default, will perform a full page redirect to the sign-in page of the provider (Google, Facebook…). This is recommended for mobile apps.
  • The popup flow will open a popup to the sign-in page of the provider. If the popup is blocked by the browser, it will fall back to a full page redirect.

Available callbacks

signInSuccessWithAuthResult(authResult, redirectUrl)

signInSuccessWithAuthResult 回调在用户成功登录时调用。 此处提供的 authResult 是一个 firebaseui.auth.AuthResult 对象,其中包括当前登录的用户、用于登录用户的凭据、指示用户是新用户还是现有用户的附加用户信息以及操作输入“登录”或“链接”之类的内容。 此回调将在未来取代 signInSuccess

参数:

NameTypeOptionalDescription
authResultfirebaseui.auth.AuthResultNoThe AuthResult of successful sign-in operation. The AuthResult object has same signature as firebase.auth.UserCredential .
redirectUrlstringYesThe URL where the user is redirected after the callback finishes. It will only be given if you overwrite the sign-in success URL .

应返回: boolean

如果回调返回 true ,则页面自动重定向 视情况而定:

  • If no signInSuccessUrl parameter was given in the URL (See: Overwriting the sign-in success URL ) then the default signInSuccessUrl in config is used.
  • If the value is provided in the URL, that value will be used instead of the static signInSuccessUrl in config.

如果回调返回 false 或什么都没有,则页面不会自动 重定向。

signInSuccess(currentUser, credential, redirectUrl)

此回调将被弃用,并由采用 firebaseui.auth.AuthResultsignInSuccessWithAuthResult 取代。

参数:

NameTypeOptionalDescription
currentUserfirebase.UserNoThe logged in user.
credentialfirebase.auth.AuthCredentialYesThe credential used to sign in the user.
redirectUrlstringYesThe URL where the user is redirected after the callback finishes. It will only be given if you overwrite the sign-in success URL .

应返回: boolean

如果回调返回 true ,则页面自动重定向 视情况而定:

  • If no signInSuccessUrl parameter was given in the URL (See: Overwriting the sign-in success URL ) then the default signInSuccessUrl in config is used.
  • If the value is provided in the URL, that value will be used instead of the static signInSuccessUrl in config.

如果回调返回 false 或什么都没有,则页面不会自动 重定向。

signInFailure(error)

signInFailure 回调用于处理任何不可恢复的错误 在登录过程中遇到。 此处提供的错误是 firebaseui.auth.AuthUIError 错误 以下属性。

firebaseui.auth.AuthUIError 属性:

NameTypeOptionalDescription
codestringNoThe corresponding error code. Currently the only error code supported is firebaseui/anonymous-upgrade-merge-conflict
credentialfirebase.auth.AuthCredentialYesThe existing non-anonymous user credential the user tried to sign in with.

应返回: Promise|void

FirebaseUI 将等待返回的承诺来处理报告的错误 在清除 UI 之前。 如果没有返回承诺,UI 将被清除 完成。 即使此回调已解决, signInSuccessWithAuthResult 不会触发回调。

当启用 autoUpgradeAnonymousUsers 时需要此回调。

uiShown()

此回调在首次呈现小部件 UI 时触发。 这是 对于应用程序应该在之前显示自定义加载器的情况很有用 显示 FirebaseUI。

Example with all parameters used

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />
    <script type="text/javascript">
      // FirebaseUI config.
      var uiConfig = {
        callbacks: {
          signInSuccessWithAuthResult: function(authResult, redirectUrl) {
            var user = authResult.user;
            var credential = authResult.credential;
            var isNewUser = authResult.additionalUserInfo.isNewUser;
            var providerId = authResult.additionalUserInfo.providerId;
            var operationType = authResult.operationType;
            // Do something with the returned AuthResult.
            // Return type determines whether we continue the redirect automatically
            // or whether we leave that to developer to handle.
            return true;
          },
          signInFailure: function(error) {
            // Some unrecoverable error occurred during sign-in.
            // Return a promise when error handling is completed and FirebaseUI
            // will reset, clearing any UI. This commonly occurs for error code
            // 'firebaseui/anonymous-upgrade-merge-conflict' when merge conflict
            // occurs. Check below for more details on this.
            return handleUIError(error);
          },
          uiShown: function() {
            // The widget is rendered.
            // Hide the loader.
            document.getElementById('loader').style.display = 'none';
          }
        },
        credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
        // Query parameter name for mode.
        queryParameterForWidgetMode: 'mode',
        // Query parameter name for sign in success url.
        queryParameterForSignInSuccessUrl: 'signInSuccessUrl',
        // 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,
          {
            provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
            // Whether the display name should be displayed in the Sign Up page.
            requireDisplayName: true
          },
          {
            provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
            // Invisible reCAPTCHA with image challenge and bottom left badge.
            recaptchaParameters: {
              type: 'image',
              size: 'invisible',
              badge: 'bottomleft'
            }
          },
          firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
        ],
        // Set to true if you only have a single federated provider like
        // firebase.auth.GoogleAuthProvider.PROVIDER_ID and you would like to
        // immediately redirect to the provider's site instead of showing a
        // 'Sign in with Provider' button first. In order for this to take
        // effect, the signInFlow option must also be set to 'redirect'.
        immediateFederatedRedirect: false,
        // tosUrl and privacyPolicyUrl accept either url string or a callback
        // function.
        // Terms of service url/callback.
        tosUrl: '<your-tos-url>',
        // Privacy policy url/callback.
        privacyPolicyUrl: function() {
          window.location.assign('<your-privacy-policy-url>');
        }
      };

      var ui = new firebaseui.auth.AuthUI(firebase.auth());
      // The start method will wait until the DOM is loaded.
      ui.start('#firebaseui-auth-container', uiConfig);
    </script>
  </head>
  <body>
    <!-- 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></div>
    <div>Loading...</div>
  </body>
</html>

Upgrading anonymous users

Enabling anonymous user upgrade

当匿名用户登录或注册永久帐户时,您希望 以确保用户可以继续他们在注册之前所做的事情。 例如,匿名用户的购物车中可能有商品。 在结帐时,您提示用户登录或注册。 用户是之后 已登录,用户的购物车应包含用户添加的任何项目 匿名登录时。

为了支持这种行为,FirebaseUI 可以轻松“升级”匿名 帐户到永久帐户。 为此,只需设置 autoUpgradeAnonymousUsers 在配置登录 UI 时设置为 true (此选项已被禁用 默认)。

FirebaseUI 使用 Firebase 将新凭证与匿名帐户关联起来 Auth 的 linkWithCredential 方法:

anonymousUser.linkWithCredential(permanentCredential);

用户将在流程结束时保留相同的 uid 并且所有数据都已键入 在该标识符上仍将与同一用户相关联。

FirebaseUI 中的电子邮件链接登录也支持匿名用户升级。 触发电子邮件链接选项的匿名用户将在单击返回时 链接,升级为电子邮件链接用户。 但是,必须在电子邮件 signInOption 中将 forceSameDevice 设置为 true 。 这是为了确保当用户单击链接时,它会在同一时间打开 初始匿名用户所在的设备/浏览器。

Handling anonymous user upgrade merge conflicts

在某些情况下,最初匿名登录的用户试图 升级到现有的 Firebase 用户。 例如,用户可能已经注册 在另一台设备上使用 Google 凭据。 当尝试升级到 现有的 Google 用户,将抛出错误 auth/credential-already-in-use 作为现有用户的 Firebase Auth 不能链接到另一个现有用户。 没有两个用户可以共享相同的凭据。 在这种情况下,两个用户数据 必须在丢弃一个用户(通常是匿名用户)之前合并。 在上面的案例中,匿名用户购物车将被复制到本地, 匿名用户将被删除,然后该用户使用 永久凭证。 临时存储的匿名用户数据将被 复制回非匿名用户。

FirebaseUI 将触发带有错误代码的 signInFailure 回调 firebaseui/anonymous-upgrade-merge-conflict 发生上述情况时。 错误 对象还将包含永久凭证。 应在回调中触发使用永久凭证登录 完成登录。 在登录之前可以通过 auth.signInWithCredential(error.credential) ,匿名用户的数据 必须复制并删除匿名用户。 登录完成后, 必须将数据复制回非匿名用户。 下面的一个例子 说明如果使用 Firebase 持久保存用户数据,此流程将如何工作 实时数据库。

示例:

// 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: {
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // Process result. This will not trigger on merge conflicts.
      // On success redirect to signInSuccessUrl.
      return true;
    },
    // 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;
      // If using Firebase Realtime Database. The anonymous user data has to be
      // copied to the non-anonymous user.
      var app = firebase.app();
      // Save anonymous user data first.
      return app.database().ref('users/' + firebase.auth().currentUser.uid)
          .once('value')
          .then(function(snapshot) {
            data = snapshot.val();
            // This will trigger onAuthStateChanged listener which
            // could trigger a redirect to another page.
            // Ensure the upgrade flow is not interrupted by that callback
            // and that this is given enough time to complete before
            // redirection.
            return firebase.auth().signInWithCredential(cred);
          })
          .then(function(user) {
            // Original Anonymous Auth instance now has the new user.
            return app.database().ref('users/' + user.uid).set(data);
          })
          .then(function() {
            // Delete anonymnous user.
            return anonymousUser.delete();
          }).then(function() {
            // Clear data in case a new user signs in, and the state change
            // triggers.
            data = null;
            // FirebaseUI will reset and the UI cleared when this promise
            // resolves.
            // signInSuccessWithAuthResult will not run. Successful sign-in
            // logic has to be run explicitly.
            window.location.assign('<url-to-redirect-to-on-success>');
          });

    }
  }
});

Multi-tenancy support

对于 GCIP 客户,您可以构建一个 使用 FirebaseUI 的租户特定登录页面。 确保您已启用 为您的项目提供多租户并配置您的租户。 见 多租户快速入门 学习如何。

此功能需要 firebase 6.6.0 或更高版本。

要将 FirebaseUI 与多租户一起使用,您需要在 在调用 ui.start() 之前传递给 FirebaseUI 的 Auth 实例。

// The Firebase Auth instance.
var auth = firebase.auth();
// Initialize FirebaseUI.
var ui = new firebaseui.auth.AuthUI(auth);
// Set the tenant ID on Auth instance.
auth.tenantId = selectedTenantId;
// Start the sign-in flow in selected tenant.
// All sign-in attempts will now use this tenant ID.
ui.start('#firebaseui-auth-container', selectedTenantConfig);

FirebaseUI 只为您处理登录流程,您仍然需要构建 您自己的 UI,让最终用户选择要登录的租户。 你可以参考这个例子 指南

还有一个 快速入门 应用程序可用于演示如何使用 两个启用了不同身份提供者集的租户的 FirebaseUI。

Customizing FirebaseUI for authentication

目前,FirebaseUI 不提供开箱即用的定制。 但是,那 小部件周围的 HTML 不受它的影响,因此您可以显示您想要的所有内容 想要围绕小部件容器。

Advanced

FirebaseUI widget modes

初始化后,FirebaseUI 将在 URL 中查找 mode 参数。 根据此参数的值,它将触发特定模式。 什么时候 没有找到 mode 参数,默认为登录模式。

您可以使用 queryParameterForWidgetMode 更改此参数的名称 配置参数。

Query parameter valueDescription
?mode=selectSign-in mode

示例:

https://<url-of-the-widget>?mode=select

Overwriting the sign-in success URL

您可以将查询参数传递给小部件的 URL,这将覆盖 URL 用户在成功登录后被重定向到。 如果你这样做,你必须设置 配置 signInSuccessUrl 值(即使它将被覆盖)。 以这种方式传递重定向 URL 时, signInSuccessWithAuthResult 回调将接收值作为 redirectUrl 参数。

在使用 signInSuccessUrl 参数,否则 FirebaseUI 会直接重定向到 指定的网址。

您可以使用以下命令更改此参数的名称 queryParameterForSignInSuccessUrl 配置参数。

示例:

https://?mode=select&signInSuccessUrl=signedIn.html 将 将用户重定向到 https:///signedIn.html 成功的登录流程。

Developer Setup

Dependencies

要设置开发环境以从源代码构建 FirebaseUI,您必须 安装以下内容:

  • Node.js (>= 6.0.0)
  • npm (should be included with Node.js)
  • Java SE Runtime Environment 8

为了运行演示和测试,您还必须:

  • Python (2.7)

下载 FirebaseUI 源及其依赖项:

git clone https://github.com/firebase/firebaseui-web.git
cd firebaseui-web
npm install

Building FirebaseUI

要构建库,请运行:

npm run build

这将在 dist/ 文件夹。

要构建本地化的 JavaScript 二进制文件,请运行:

npm run build build-js-{LANGUAGE_CODE}

其中 {LANGUAGE_CODE} 被替换为 你想要的语言代码 。 例如,法语二进制 可以使用 npm run build build-js-fr 构建。 这将创建一个二进制文件 firebaseui__fr.jsdist/ 文件夹中。

为带有下划线的语言代码构建名称,例如。 zh_tw , zh_cn , pt_pt 将映射到 zh-TWxh-CNpt-PT 。 下划线将替换为 连字符和后续字符将大写。

npm run build build-js-zh-TW

这将在 dist/ 文件夹中创建一个二进制文件 firebaseui__zh_tw.js

要构建本地化的 npm FirebaseUI 模块,

npm run build build-npm-{LANGUAGE_CODE}

请运行:确保 LANGUAGE_CODE 中的所有下划线符号都替换为 破折号。 这将生成 dist/npm__{LANGUAGE_CODE}.js 。 然后您可以导入/要求它:

import firebaseui from './npm__{LANGUAGE_CODE}';

为带有下划线的语言代码构建名称,例如。 zh_tw , zh_cn , pt_pt 将映射到 zh-TWxh-CNpt-PT 。 下划线将替换为 连字符和后续字符将大写。

npm run build build-npm-zh-TW

这将在 dist/ 文件夹中创建一个二进制 npm__zh_tw.js

Running the demo app

要运行演示应用程序,您必须在 Firebase 控制台 。 复制 demo/public/sample-config.jsdemo/public/config.js

cp demo/public/sample-config.js demo/public/config.js

从 Firebase 控制台中的“将 Firebase 添加到您的网络应用程序”流程中复制数据。 接下来,运行:

npm run demo

这将启动一个本地服务器,为一个 FirebaseUI 演示应用程序提供所有本地服务 变化。 可以在 演示应用程序文件夹 中找到更多详细信息,包括 如何将应用配置为部署在 Firebase 托管实例上。

Running unit tests.

所有单元测试都可以在命令行上运行(通过 PhantomJS):

npm test

或者,单元测试可以通过运行手动运行:

npm run serve

然后,所有单元测试都可以在以下位置运行:http://localhost:4000/buildtools/all< em>tests.html 您还可以通过访问下面的每个 HTML 文件来单独运行测试 generated/tests ,例如:http://localhost:4000/generated/tests/javascript/widgets/authuitest.html

Run tests using SauceLabs

你需要一个 SauceLabs 帐户运行测试 SauceLabs。

转到您的 SauceLab 帐户,在“我的帐户”下,复制粘贴访问密钥。 现在导出以下变量,在两个终端窗口

export SAUCE_USERNAME=<your username>
export SAUCE_ACCESS_KEY=<the copy pasted access key>

然后,在一个终端窗口中,启动 SauceConnect:

./buildtools/sauce_connect.sh

记下终端中记录的“隧道标识符”值,在顶部。 在 具有导出变量的另一个终端,运行测试:

npm test -- --saucelabs --tunnelIdentifier=<the tunnel identifier>

IAP External Identities Support with FirebaseUI

您可以使用 FirebaseUI 构建身份验证页面以使用外部 身份与 谷歌云 IAP 。 可以在 此处 找到文档。

Cordova Setup

Introduction

FirebaseUI 登录小部件支持 Cordova 应用程序。 这包括 电子邮件/密码和所有 OAuth 提供商(Google、Facebook、Twitter 和 GitHub)。 受底层限制,不支持电话认证 Firebase 核心 SDK。 由于无法检测,暂不支持邮件链接认证 用户单击它以完成登录时的传入链接。

Available providers

ProviderValue
Googlefirebase.auth.GoogleAuthProvider.PROVIDER_ID
Facebookfirebase.auth.FacebookAuthProvider.PROVIDER_ID
Twitterfirebase.auth.TwitterAuthProvider.PROVIDER_ID
Githubfirebase.auth.GithubAuthProvider.PROVIDER_ID
Email and passwordfirebase.auth.EmailAuthProvider.PROVIDER_ID
Anonymousfirebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
Microsoftmicrosoft.com
Yahooyahoo.com
SAML (GCIP only)saml.*********
OIDC (GCIP only)oidc.*********

Setup and Usage

为了将 FirebaseUI 与您的 Cordova 应用程序集成,您需要 请按照以下步骤操作:

  • Install the necessary Cordova plugins, make the necessary Firebase Console changes and update your config.xml file as documented in OAuth Sign-In for Cordova
  • After you have successfully configured your application, you can use FirebaseUI in your Cordova application just like any other traditional browser applications.

设置应用程序时请记住以下几点:

  • Only redirect signInFlow is supported as Firebase Auth does not support popup mode for Cordova.
  • firebase.auth.PhoneAuthProvider.PROVIDER_ID is not currently supported.
  • As the application runs within an embedded webview, accountchooser.com will always be disabled.
  • If you are providing a Content-Security-Policy make sure you add the appropriate exceptions for FirebaseUI resources ( style-src , media-src , img-src , script-src , etc.) and underlying Firebase JS SDK.

React DOM Setup

In React DOM applications you can use the FirebaseUI Web React Wrapper .

Angular Setup

In Angular applications you can use this FirebaseUI Web Angular Wrapper from the community.

Known issues

Firebase Auth does not work in Safari private browsing

When a user has enabled the private browsing mode in Safari, the web storage is disabled. This currently results in an error being thrown upon Firebase Auth initialization. Therefore, when following the snippets above, FirebaseUI will never get initialized and no UI will be displayed.

Firebase Auth OAuth popup/redirect operations may not work when 3rd party cookies are disabled

When a user disables 3rd party cookies in their browser, the mechanism for returning the result of an OAuth popup/redirect as implemented by the underlying firebase-auth.js library may be broken on some browsers.

Tips for Single Page apps ( UI Widget is already rendered on the page warning)

When re-rendering the FirebaseUI Auth widget (for instance after signing in a user, signing her out and trying to sign her in again), it will sometimes log a warning:

UI Widget is already rendered on the page and is pending some user interaction. Only one widget instance can be rendered per page. The previous instance has been automatically reset.

This happens when the UI widget was in a pending state, i.e. the user was in the middle of performing a sign-in flow. You should generally avoid re-rendering the widget in the middle of an action, but if you do, to avoid the warning, you should use the reset() method before re-rendering the widget.

Tips for initializing a new UI instance with the same Auth instance

When trying to initialize a new UI widget with the same Auth instance, you will get an app/duplicate-app error. In general, you should keep a reference to the AuthUI instance and instead call reset() and then start(...) again to re-render the widget.

If you don't keep a reference to that AuthUI instance, you can get the reference by calling firebaseui.auth.AuthUI.getInstance(appId) where appId is the same as the optional one used to initialize the AuthUI instance. If none was provided just call firebaseui.auth.AuthUI.getInstance() .

This is the recommended way but you also have the option to delete the AuthUI instance by calling ui.delete() which returns a promise that resolves on successful deletion. You can then initialize a new UI instance with the same Auth instance without getting the app/duplicate-app error. At any time, you can only have one AuthUI instance with the same appId or the same Auth instance.

FirebaseUI is broken in IE11 when deployed on a local server accessed through localhost (but works when deployed on a remote server)

Several developers reported issues with IE11 when testing the widget integration on a server deployed locally, accessing the application through a localhost address. However, it doesn't impact applications deployed on a server (as you can verify in the demo app ).

termlist-auth-ui, fork of FirebaseUI for Web — Auth

FirebaseUI is an open-source JavaScript library for Web that provides simple, customizable UI bindings on top of Firebase SDKs to eliminate boilerplate code and promote best practices.

FirebaseUI Auth provides a drop-in auth solution that handles the UI flows for signing in users with email addresses and passwords, phone numbers, Identity Provider Sign In including Google, Facebook, GitHub, Twitter, Apple, Microsoft, Yahoo, OpenID Connect (OIDC) providers and SAML providers. It is built on top of Firebase Auth.

The FirebaseUI component implements best practices for authentication on mobile devices and websites, helping to sign-in and sign-up conversion for your app. It also handles cases like account recovery and account linking that can be security sensitive and error-prone to handle.

FirebaseUI Auth clients are also available for iOS and Android.

FirebaseUI fully supports all recent browsers. Signing in with federated providers (Google, Facebook, Twitter, GitHub, Apple, Microsoft, Yahoo, OIDC, SAML) is also supported in Cordova/Ionic environments. Additional non-browser environments(React Native…) or Chrome extensions will be added once the underlying Firebase core SDK supports them in a way that is compatible with FirebaseUI.

Table of Contents

  1. Demo
  2. Installation
  3. Usage instructions
  4. Configuration
  5. Customization
  6. Advanced
  7. Developer Setup
  8. IAP External Identities Support with FirebaseUI
  9. Cordova Setup
  10. React DOM Setup
  11. Angular Setup
  12. Known issues
  13. Release Notes

Demo

Accessible here: https://fir-ui-demo-84a6c.firebaseapp.com.

Installation

Option 1: CDN

You just need to include the following script and CSS file in the <head> tag of your page, below the initialization snippet from the Firebase Console:

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

Localized Widget

Localized versions of the widget are available through the CDN. To use a localized widget, load the localized JS library instead of the default library:

<script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth__{LANGUAGE_CODE}.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />

where {LANGUAGE_CODE} is replaced by the code of the language you want. For example, the French version of the library is available at https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth__fr.js. The list of available languages and their respective language codes can be found at LANGUAGES.md.

Right-to-left languages also require the right-to-left version of the stylesheet, available at https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth-rtl.css, instead of the default stylesheet. The supported right-to-left languages are Arabic (ar), Farsi (fa), and Hebrew (iw).

Option 2: npm Module

Install FirebaseUI and its peer-dependency Firebase via npm using the following commands:

$ npm install firebase --save
$ npm install firebaseui --save

You can then require the following modules within your source files:

var firebase = require('firebase');
var firebaseui = require('firebaseui');
// or using ES6 imports:
import * as firebaseui from 'firebaseui'

Or include the required files in your HTML, if your HTTP Server serves the files within node_modules/:

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

Option 3: Bower component

Install FirebaseUI and its dependencies via Bower using the following command:

$ bower install firebaseui --save

You can then include the required files in your HTML, if your HTTP Server serves the files within bower_components/:

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

Using FirebaseUI for Authentication

FirebaseUI includes the following flows:

  1. Interaction with Identity Providers such as Google and Facebook
  2. Phone number based authentication
  3. Sign-up and sign-in with email accounts (email/password and email link)
  4. Password reset
  5. Prevention of account duplication (activated when "One account per email address" setting is enabled in the Firebase console. This setting is enabled by default.)
  6. Account Chooser for remembering emails
  7. Integration with one-tap sign-up
  8. Ability to upgrade anonymous users through sign-in/sign-up
  9. Sign-in as a guest

Configuring sign-in providers

To use FirebaseUI to authenticate users you first need to configure each provider you want to use in their own developer app settings. Please read the Before you begin section of Firebase Authentication at the following links:

For Google Cloud's Identity Platform (GCIP) developers, you can also enable SAML and OIDC providers following the instructions:

Starting the sign-in flow

You first need to initialize your Firebase app. The firebase.auth.Auth instance should be passed to the constructor of firebaseui.auth.AuthUI. You can then call the start method with the CSS selector that determines where to create the widget, and a configuration object.

The following example shows how to set up a sign-in screen with all supported providers. Please refer to the demo application in the examples folder for a more in-depth example, showcasing a Single Page Application mode.

Firebase and FirebaseUI do not work when executed directly from a file (i.e. opening the file in your browser, not through a web server). Always run firebase serve (or your preferred local server) to test your app locally.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />
    <script type="text/javascript">
      // FirebaseUI config.
      var uiConfig = {
        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,
          firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
        ],
        // tosUrl and privacyPolicyUrl accept either url string or a callback
        // function.
        // Terms of service url/callback.
        tosUrl: '<your-tos-url>',
        // Privacy policy url/callback.
        privacyPolicyUrl: function() {
          window.location.assign('<your-privacy-policy-url>');
        }
      };

      // Initialize the FirebaseUI Widget using Firebase.
      var ui = new firebaseui.auth.AuthUI(firebase.auth());
      // The start method will wait until the DOM is loaded.
      ui.start('#firebaseui-auth-container', uiConfig);
    </script>
  </head>
  <body>
    <!-- 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>
  </body>
</html>

This is only relevant for single page apps or apps where the sign-in UI is rendered conditionally (e.g. button click)

When redirecting back from accountchooser.com, Identity Providers like Google and Facebook or email link sign-in, start() method needs to be called to finish the sign-in flow. If it requires a user interaction to start the initial sign-in process, you need to check if there is a pending redirect operation going on on page load to check whether start() needs to be called.

To check if there is a pending redirect operation to complete a sign-in attempt, check isPendingRedirect() before deciding whether to render FirebaseUI via start().

if (ui.isPendingRedirect()) {
  ui.start('#firebaseui-auth-container', uiConfig);
}

Here is how you would track the Auth state across all your pages:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script type="text/javascript">
      initApp = function() {
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var uid = user.uid;
            var phoneNumber = user.phoneNumber;
            var providerData = user.providerData;
            user.getIdToken().then(function(accessToken) {
              document.getElementById('sign-in-status').textContent = 'Signed in';
              document.getElementById('sign-in').textContent = 'Sign out';
              document.getElementById('account-details').textContent = JSON.stringify({
                displayName: displayName,
                email: email,
                emailVerified: emailVerified,
                phoneNumber: phoneNumber,
                photoURL: photoURL,
                uid: uid,
                accessToken: accessToken,
                providerData: providerData
              }, null, '  ');
            });
          } else {
            // User is signed out.
            document.getElementById('sign-in-status').textContent = 'Signed out';
            document.getElementById('sign-in').textContent = 'Sign in';
            document.getElementById('account-details').textContent = 'null';
          }
        }, function(error) {
          console.log(error);
        });
      };

      window.addEventListener('load', function() {
        initApp();
      });
    </script>
  </head>
  <body>
    <h1>Welcome to My Awesome App</h1>
    <div id="sign-in-status"></div>
    <div id="sign-in"></div>
    <pre id="account-details"></pre>
  </body>
</html>

Configuration

FirebaseUI supports the following configuration parameters.

NameRequiredDescription
autoUpgradeAnonymousUsersNoWhether to automatically upgrade existing anonymous users on sign-in/sign-up. See Upgrading anonymous users.
Default: false When set to true, signInFailure callback is required to be provided to handle merge conflicts.
callbacksNoAn object of developers callbacks after specific events.
Default: {}
credentialHelperNoThe Credential Helper to use. See Credential Helper.
Default: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM
queryParameterForSignInSuccessUrlNoThe redirect URL parameter name for the sign-in success URL. See Overwriting the sign-in success URL.
Default: "signInSuccessUrl"
queryParameterForWidgetModeNoThe redirect URL parameter name for the “mode” of the Widget. See FirebaseUI widget modes.
Default: "mode"
signInFlowNoThe sign-in flow to use for IDP providers: redirect or popup.
Default: "redirect"
immediateFederatedRedirectNoA boolean which determines whether to immediately redirect to the provider's site or instead show the default 'Sign in with Provider' button when there is only a single federated provider in signInOptions. In order for this option to take effect, the signInOptions must only hold a single federated provider (like 'google.com') and signInFlow must be set to 'redirect'.
signInOptionsYesThe list of providers enabled for signing into your app. The order you specify them will be the order they are displayed on the sign-in provider selection screen.
signInSuccessUrlNoThe URL where to redirect the user after a successful sign-in. Required when the signInSuccessWithAuthResult callback is not used or when it returns true.
tosUrlYesThe URL of the Terms of Service page or a callback function to be invoked when Terms of Service link is clicked.
privacyPolicyUrlYesThe URL of the Privacy Policy page or a callback function to be invoked when Privacy Policy link is clicked.

Credential Helper

The role of a credential helper is to help your users sign into your website. When one is enabled, your users will be prompted with email addresses and usernames they have saved from your app or other applications. FirebaseUI supports the following credential helpers:

accountchooser.com

When accountchooser.com is enabled (enabled by default), upon signing in or signing up with email, the user will be redirected to the accountchooser.com website and will be able to select one of their saved accounts. You can disable it by specifying the value below. This feature is always disabled for non HTTP/HTTPS environments.

One-tap sign-up

Note: The beta test program for this API is currently closed.

One-tap sign-up provides seamless authentication flows to your users with Google's one tap sign-up and automatic sign-in APIs. With one tap sign-up, users are prompted to create an account with a dialog that's inline with FirebaseUI NASCAR screen. With just one tap, they get a secure, token-based, passwordless account with your service, protected by their Google Account. As the process is frictionless, users are much more likely to register. Returning users are signed in automatically, even when they switch devices or platforms, or after their session expires. One-tap sign-up integrates with FirebaseUI and if you request Google OAuth scopes, you will still get back the expected Google OAuth access token even if the user goes through the one-tap flow. However, in that case 'redirect' flow is always used even when 'popup' is specified. In addition, if you choose to force prompt for Google sign-in, one-tap auto sign-in will be automatically disabled. One-tap is an additive feature and is only supported in the latest evergreen modern browser environments. For more information on how to configure one-tap sign-up, refer to the one-tap get started guide.

The following example shows how to configure one-tap sign-up with FirebaseUI. Along with the corresponding one-tap credentialHelper, clientId and authMethod have to be provided with the Firebase Google provider:

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      // Google provider must be enabled in Firebase Console to support one-tap
      // sign-up.
      provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
      // Required to enable this provider in one-tap sign-up.
      authMethod: 'https://accounts.google.com',
      // Required to enable ID token credentials for this provider.
      // This can be obtained from the Credentials page of the Google APIs
      // console.
      clientId: 'xxxxxxxxxxxxxxxxx.apps.googleusercontent.com'
    },
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.TwitterAuthProvider.PROVIDER_ID,
    firebase.auth.GithubAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
  ],
  // Required to enable one-tap sign-up credential helper.
  credentialHelper: firebaseui.auth.CredentialHelper.GOOGLE_YOLO
});
// Auto sign-in for returning users is enabled by default except when prompt is
// not 'none' in the Google provider custom parameters. To manually disable:
ui.disableAutoSignIn();

Auto sign-in for returning users can be disabled by calling ui.disableAutoSignIn(). This may be needed if the FirebaseUI sign-in page is being rendered after the user signs out.

To see FirebaseUI in action with one-tap sign-up, check out the FirebaseUI demo app.

Credential HelperValue
accountchooser.comfirebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM
One-tap sign-upfirebaseui.auth.CredentialHelper.GOOGLE_YOLO
None (disable)firebaseui.auth.CredentialHelper.NONE

Available providers

ProviderValue
Googlefirebase.auth.GoogleAuthProvider.PROVIDER_ID
Facebookfirebase.auth.FacebookAuthProvider.PROVIDER_ID
Twitterfirebase.auth.TwitterAuthProvider.PROVIDER_ID
Githubfirebase.auth.GithubAuthProvider.PROVIDER_ID
Email and passwordfirebase.auth.EmailAuthProvider.PROVIDER_ID
Phone numberfirebase.auth.PhoneAuthProvider.PROVIDER_ID
Anonymousfirebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
Appleapple.com
Microsoftmicrosoft.com
Yahooyahoo.com
SAML (GCIP only)saml.*********
OIDC (GCIP only)oidc.*********

Configure OAuth providers

To specify custom scopes, or custom OAuth parameters per provider, you can pass an object instead of just the provider value:

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.
  ]
});

Generic OAuth provider

You can let your users authenticate with FirebaseUI using OAuth providers like Apple, Microsoft Azure Active Directory and Yahoo by integrating generic OAuth Login into your app.

You just need to pass the provider ID in signInOptions, FirebaseUI provides the default configurations for the sign in button(button color, icon and display name):

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    'apple.com',
    'microsoft.com',
    'yahoo.com',
  ]
});

You can also override these default configurations with your own custom ones. Generic OAuth providers' signInOptions support the following configuration parameters.

NameRequiredDescription
providerYesThe provider ID, eg. microsoft.com.
providerNameNoThe provider name displayed to end users (sign in button/linking prompt), eg. "Microsoft" Default: provider ID
buttonColorNoThe color of sign in button. The css of the button can be overwritten with the attribute/value in the HTML element: data-provider-id="providerId"
iconUrlNoThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
scopesNoThe list of additional OAuth 2.0 scopes beyond basic profile that you want to request from the authentication provider.
customParametersNoThe list of additional custom OAuth parameters that you want to send with the OAuth request.
loginHintKeyNoThe key of the custom parameter, with which the login hint can be passed to the provider. This is useful in case a user previously signs up with an IdP like Microsoft and then tries to sign in with email using the same Microsoft email. FirebaseUI can then ask the user to sign in with that email to the already registered account with Microsoft. For Microsoft and Yahoo, this field is `login_hint`.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'microsoft.com',
      providerName: 'Microsoft',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>',
      loginHintKey: 'login_hint',
      scopes: [
        'mail.read'
      ],
      customParameters: {
        prompt: 'consent'
      }
    }
  ]
});

OpenID Connect (OIDC) providers (GCIP only)

For GCIP customers, you can enable your app for OpenID Connect (OIDC) authentication with FirebaseUI.

OIDC providers' signInOptions support the following configuration parameters.

NameRequiredDescription
providerYesThe provider ID, eg. oidc.myProvider.
providerNameNoThe provider name displayed to end users (sign in button/linking prompt). Default: provider ID
buttonColorYesThe color of sign in button. The css of the button can be overwritten with attribute/value in the HTML element: data-provider-id="providerId"
iconUrlYesThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
customParametersNoThe list of additional custom parameters that the OIDC provider supports.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'oidc.myProvider`,
      providerName: 'MyOIDCProvider',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>',
      customParameters: {
        OIDCSupportedParameter: 'value'
      }
    }
  ]
});

SAML providers (GCIP only)

For GCIP customers, you can enable your app for SAML authentication with FirebaseUI.

SAML providers' signInOptions support the following configuration parameters.

NameRequiredDescription
providerYesThe provider ID, eg. saml.myProvider.
providerNameNoThe provider name displayed to end users (sign in button/linking prompt). Default: provider ID
buttonColorYesThe color of sign in button. The css of the button can be overwritten with attribute/value in the HTML element: data-provider-id="providerId"
iconUrlYesThe URL of the Identity Provider's icon. This will be displayed on the provider's sign-in button, etc.
ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: 'saml.myProvider',
      providerName: 'MySAMLProvider',
      buttonColor: '#2F2F2F',
      iconUrl: '<icon-url-of-sign-in-button>'
    }
  ]
});

Configure Email Provider

You can configure either email/password or email/link sign-in with FirebaseUI by providing the relevant object in the configuration signInOptions array.

NameTypeRequiredDescription
providerstringYesFor email sign-in, this should be firebase.auth.EmailAuthProvider.PROVIDER_ID.
requireDisplayNamebooleanNoDefines whether to require the user to provide a display name during email and password sign up.
Default: true
signInMethodstringNoDefines whether to use email and password or email link authentication. This should be firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD for email and password sign-in, firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD for email link authentication.
Default: firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD
forceSameDevicebooleanNoWhether to force same device flow. If false, opening the link on a different device will display a message instructing the user to open the link on the same device or browser. This should be true when used with anonymous user upgrade flows. This is only relevant to email link sign-in. Default: false
emailLinkSignInfunctionNoDefines the optional callback function to return firebase.auth.ActionCodeSettings configuration to use when sending the link. This provides the ability to specify how the link can be handled, custom dynamic link, additional state in the deep link, etc. When not provided, the current URL is used and a web only flow is triggered. This is only relevant to email link sign-in.

Email and Password

Email and password authentication is the default sign-in method for Email providers. The EmailAuthProvider with email and password can be configured to require the user to enter a display name (defaults to true).

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      requireDisplayName: false
    }
  ]
});

Email Link Authentication

FirebaseUI supports sign-in and sign-up with email links. Using email link sign-in with FirebaseUI comes with the following benefits:

  • End to end support for email link sign-in with only a few configuration lines.
  • Enforces security and privacy best practices.
  • Ability to force same device flows or allow cross device flows where a user can start the flow on one device and end it on another. This also covers Android and iOS where email link sign-in is also supported with FirebaseUI-android and FirebaseUI-ios.
  • Ability to switch to email link sign-in while continuing to sign-in existing users with email and password.
  • Ability to support account linking, where an existing email link user signing in with Facebook for the first time using the same email will have both accounts merged so they can sign in with either (Facebook or email link) going forward.
  • Ability to support anonymous user upgrade as long as the flow starts and ends on the same device. Users opening the link on a different device will be notified to open the link on the same device where the flow started.

The sample code below demonstrates how to configure email link sign-in with FirebaseUI. In this example, cross device flows are allowed and additional state is passed in the URL, as well as the ability to configure the link to open via mobile application too.

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
      // Use email link authentication and do not require password.
      // Note this setting affects new users only.
      // For pre-existing users, they will still be prompted to provide their
      // passwords on sign-in.
      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'
          }
        };
      }
    }
  ]
});

When rendering the sign-in UI conditionally (relevant for single page apps), use ui.isPendingRedirect() to detect if the URL corresponds to a sign-in with email link and the UI needs to be rendered to complete sign-in. You can also just use firebase.auth().isSignInWithEmailLink(window.location.href).

// 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);
}

Additional state passed in the url can be retrieved on sign-in completion via the signInSuccess callbacks.

// ...
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
  // If a user signed in with email link, ?showPromo=1234 can be obtained from
  // window.location.href.
  // ...
  return false;
}

FirebaseUI uses the history API to clear the URL from query parameters related to email link sign-in after the one-time code is processed. This prevents the user from re-triggering the sign-in completion flow again on page reload or if the user signs out and tries to sign in again in a single page application, etc.

When same device flows are not enforced, a user going through account linking flow (eg. user signing in with Facebook with an email that belongs to an existing email link user) opening the link on a different device would be given the choice to continue sign-in with email link without merging the Facebook credential or instructed to open the link on the same device where the flow was initiated to successfully merge both accounts.

You cannot use email/password and email/link sign-in at the same time. Only one mode can be configured at a time. However, if you previously signed up users with passwords. Switching to email/link will only apply to new users and existing password users will continue to be prompted for password on sign-in.

Configure Phone Provider

The PhoneAuthProvider can be configured with custom reCAPTCHA parameters whether reCAPTCHA is visible or invisible (defaults to normal). Refer to the reCAPTCHA API docs for more details.

The default country to select in the phone number input can also be set. List of supported country codes. If unspecified, the phone number input will default to the United States (+1).

The countries to select can also be configured with blacklistedCountries or whitelistedCountries. It accepts either ISO (alpha-2) or E164 (prefix with '+') formatted country code. Invalid country code will be ignored. whitelistedCountries and blacklistedCountries cannot be specified at the same time.

The following options are currently supported. Any other parameters will be ignored.

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',
      // You can provide a 'whitelistedCountries' or 'blacklistedCountries' for
      // countries to select. It takes an array of either ISO (alpha-2) or
      // E164 (prefix with '+') formatted country codes. If 'defaultCountry' is
      // not whitelisted or is blacklisted, the default country will be set to the
      // first country available (alphabetical order). Notice that
      // 'whitelistedCountries' and 'blacklistedCountries' cannot be specified
      // at the same time.
      whitelistedCountries: ['US', '+44']
    }
  ]
});

Configure Anonymous Provider

The AnonymousAuthProvider can be enabled to let users continue as a guest. If a user is already signed in anonymously, clicking this sign-in option will keep the same current anonymous user. In addition, when auto-upgrade for anonymous users is enabled in addition to this option and a user is already signed in anonymously, clicking this sign-in option will also keep the same current anonymous user.

ui.start('#firebaseui-auth-container', {
  signInOptions: [
    {
      provider: firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
    }
  ]
});

Sign In Flows

Two sign in flows are available:

  • redirect, the default, will perform a full page redirect to the sign-in page of the provider (Google, Facebook…). This is recommended for mobile apps.
  • The popup flow will open a popup to the sign-in page of the provider. If the popup is blocked by the browser, it will fall back to a full page redirect.

Available callbacks

signInSuccessWithAuthResult(authResult, redirectUrl)

The signInSuccessWithAuthResult callback is invoked when user signs in successfully. The authResult provided here is a firebaseui.auth.AuthResult object, which includes the current logged in user, the credential used to sign in the user, additional user info indicating if the user is new or existing and operation type like 'signIn' or 'link'. This callback will replace signInSuccess in future.

Parameters:

NameTypeOptionalDescription
authResultfirebaseui.auth.AuthResultNoThe AuthResult of successful sign-in operation. The AuthResult object has same signature as firebase.auth.UserCredential.
redirectUrlstringYesThe URL where the user is redirected after the callback finishes. It will only be given if you overwrite the sign-in success URL.

Should return: boolean

If the callback returns true, then the page is automatically redirected depending on the case:

  • If no signInSuccessUrl parameter was given in the URL (See: Overwriting the sign-in success URL) then the default signInSuccessUrl in config is used.
  • If the value is provided in the URL, that value will be used instead of the static signInSuccessUrl in config.

If the callback returns false or nothing, the page is not automatically redirected.

signInSuccess(currentUser, credential, redirectUrl)

This callback will be deprecated and will be replaced by signInSuccessWithAuthResult which takes firebaseui.auth.AuthResult.

Parameters:

NameTypeOptionalDescription
currentUserfirebase.UserNoThe logged in user.
credentialfirebase.auth.AuthCredentialYesThe credential used to sign in the user.
redirectUrlstringYesThe URL where the user is redirected after the callback finishes. It will only be given if you overwrite the sign-in success URL.

Should return: boolean

If the callback returns true, then the page is automatically redirected depending on the case:

  • If no signInSuccessUrl parameter was given in the URL (See: Overwriting the sign-in success URL) then the default signInSuccessUrl in config is used.
  • If the value is provided in the URL, that value will be used instead of the static signInSuccessUrl in config.

If the callback returns false or nothing, the page is not automatically redirected.

signInFailure(error)

The signInFailure callback is provided to handle any unrecoverable error encountered during the sign-in process. The error provided here is a firebaseui.auth.AuthUIError error with the following properties.

firebaseui.auth.AuthUIError properties:

NameTypeOptionalDescription
codestringNoThe corresponding error code. Currently the only error code supported is firebaseui/anonymous-upgrade-merge-conflict
credentialfirebase.auth.AuthCredentialYesThe existing non-anonymous user credential the user tried to sign in with.

Should return: Promise<void>|void

FirebaseUI will wait for the returned promise to handle the reported error before clearing the UI. If no promise is returned, the UI will be cleared on completion. Even when this callback resolves, signInSuccessWithAuthResult callback will not be triggered.

This callback is required when autoUpgradeAnonymousUsers is enabled.

uiShown()

This callback is triggered the first time the widget UI is rendered. This is useful for cases where the application should display a custom loader before FirebaseUI is displayed.

Example with all parameters used

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sample FirebaseUI App</title>
    <!-- *******************************************************************************************
       * TODO(DEVELOPER): Paste the initialization snippet from:
       * Firebase Console > Overview > Add Firebase to your web app. *
       ***************************************************************************************** -->
    <script src="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.3.0/firebase-ui-auth.css" />
    <script type="text/javascript">
      // FirebaseUI config.
      var uiConfig = {
        callbacks: {
          signInSuccessWithAuthResult: function(authResult, redirectUrl) {
            var user = authResult.user;
            var credential = authResult.credential;
            var isNewUser = authResult.additionalUserInfo.isNewUser;
            var providerId = authResult.additionalUserInfo.providerId;
            var operationType = authResult.operationType;
            // Do something with the returned AuthResult.
            // Return type determines whether we continue the redirect automatically
            // or whether we leave that to developer to handle.
            return true;
          },
          signInFailure: function(error) {
            // Some unrecoverable error occurred during sign-in.
            // Return a promise when error handling is completed and FirebaseUI
            // will reset, clearing any UI. This commonly occurs for error code
            // 'firebaseui/anonymous-upgrade-merge-conflict' when merge conflict
            // occurs. Check below for more details on this.
            return handleUIError(error);
          },
          uiShown: function() {
            // The widget is rendered.
            // Hide the loader.
            document.getElementById('loader').style.display = 'none';
          }
        },
        credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
        // Query parameter name for mode.
        queryParameterForWidgetMode: 'mode',
        // Query parameter name for sign in success url.
        queryParameterForSignInSuccessUrl: 'signInSuccessUrl',
        // 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,
          {
            provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
            // Whether the display name should be displayed in the Sign Up page.
            requireDisplayName: true
          },
          {
            provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
            // Invisible reCAPTCHA with image challenge and bottom left badge.
            recaptchaParameters: {
              type: 'image',
              size: 'invisible',
              badge: 'bottomleft'
            }
          },
          firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
        ],
        // Set to true if you only have a single federated provider like
        // firebase.auth.GoogleAuthProvider.PROVIDER_ID and you would like to
        // immediately redirect to the provider's site instead of showing a
        // 'Sign in with Provider' button first. In order for this to take
        // effect, the signInFlow option must also be set to 'redirect'.
        immediateFederatedRedirect: false,
        // tosUrl and privacyPolicyUrl accept either url string or a callback
        // function.
        // Terms of service url/callback.
        tosUrl: '<your-tos-url>',
        // Privacy policy url/callback.
        privacyPolicyUrl: function() {
          window.location.assign('<your-privacy-policy-url>');
        }
      };

      var ui = new firebaseui.auth.AuthUI(firebase.auth());
      // The start method will wait until the DOM is loaded.
      ui.start('#firebaseui-auth-container', uiConfig);
    </script>
  </head>
  <body>
    <!-- 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>
  </body>
</html>

Upgrading anonymous users

Enabling anonymous user upgrade

When an anonymous user signs in or signs up with a permanent account, you want to be sure the user can continue with what they were doing before signing up. For example, an anonymous user might have items in their shopping cart. At check-out, you prompt the user to sign in or sign up. After the user is signed in, the user's shopping cart should contain any items the user added while signed in anonymously.

To support this behavior, FirebaseUI makes it easy to "upgrade" an anonymous account to a permanent account. To do so, simply set autoUpgradeAnonymousUsers to true when you configure the sign-in UI (this option is disabled by default).

FirebaseUI links the new credential with the anonymous account using Firebase Auth's linkWithCredential method:

anonymousUser.linkWithCredential(permanentCredential);

The user will retain the same uid at the end of the flow and all data keyed on that identifier would still be associated with that same user.

Anonymous user upgrade is also supported by email link sign-in in FirebaseUI. An anonymous user triggering the email link option will, on return from clicking the link, upgrade to an email link user. However, forceSameDevice must be set to true in the email signInOption. This is to ensure that when the user clicks the link, it is opened on the same device/browser where the initial anonymous user exists.

Handling anonymous user upgrade merge conflicts

There are cases when a user, initially signed in anonymously, tries to upgrade to an existing Firebase user. For example, a user may have signed up with a Google credential on another device. When trying to upgrade to the existing Google user, an error auth/credential-already-in-use will be thrown by Firebase Auth as an existing user cannot be linked to another existing user. No two users can share the same credential. In that case, both user data have to be merged before one user is discarded (typically the anonymous user). In the case above, the anonymous user shopping cart will be copied locally, the anonymous user will be deleted and then the user is signed in with the permanent credential. The anonymous user data in temporary storage will be copied back to the non-anonymous user.

FirebaseUI will trigger the signInFailure callback with an error code firebaseui/anonymous-upgrade-merge-conflict when the above occurs. The error object will also contain the permanent credential. Sign-in with the permanent credential should be triggered in the callback to complete sign-in. Before sign-in can be completed via auth.signInWithCredential(error.credential), the data of the anonymous user must be copied and the anonymous user deleted. After sign-in completion, the data has to be copied back to the non-anonymous user. An example below illustrates how this flow would work if user data is persisted using Firebase Realtime Database.

Example:

// 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: {
    signInSuccessWithAuthResult: function(authResult, redirectUrl) {
      // Process result. This will not trigger on merge conflicts.
      // On success redirect to signInSuccessUrl.
      return true;
    },
    // 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;
      // If using Firebase Realtime Database. The anonymous user data has to be
      // copied to the non-anonymous user.
      var app = firebase.app();
      // Save anonymous user data first.
      return app.database().ref('users/' + firebase.auth().currentUser.uid)
          .once('value')
          .then(function(snapshot) {
            data = snapshot.val();
            // This will trigger onAuthStateChanged listener which
            // could trigger a redirect to another page.
            // Ensure the upgrade flow is not interrupted by that callback
            // and that this is given enough time to complete before
            // redirection.
            return firebase.auth().signInWithCredential(cred);
          })
          .then(function(user) {
            // Original Anonymous Auth instance now has the new user.
            return app.database().ref('users/' + user.uid).set(data);
          })
          .then(function() {
            // Delete anonymnous user.
            return anonymousUser.delete();
          }).then(function() {
            // Clear data in case a new user signs in, and the state change
            // triggers.
            data = null;
            // FirebaseUI will reset and the UI cleared when this promise
            // resolves.
            // signInSuccessWithAuthResult will not run. Successful sign-in
            // logic has to be run explicitly.
            window.location.assign('<url-to-redirect-to-on-success>');
          });

    }
  }
});

Multi-tenancy support

For GCIP customers, you can build a tenant-specific sign-in page with FirebaseUI. Make sure you've enabled multi-tenancy for your project and configured your tenants. See the Multi-tenancy quickstart to learn how.

This feature requires firebase version 6.6.0 or higher.

To use FirebaseUI with multi-tenancy, you need to set the tenant ID on the Auth instance being passed to FirebaseUI before calling ui.start().

// The Firebase Auth instance.
var auth = firebase.auth();
// Initialize FirebaseUI.
var ui = new firebaseui.auth.AuthUI(auth);
// Set the tenant ID on Auth instance.
auth.tenantId = selectedTenantId;
// Start the sign-in flow in selected tenant.
// All sign-in attempts will now use this tenant ID.
ui.start('#firebaseui-auth-container', selectedTenantConfig);

FirebaseUI only handles the sign-in flows for you, you will still need to build your own UI to let the end users select a tenant to sign in with. You can refer to the example in this guide.

There is also a quickstart app available to demonstrate how to build a single sign-in page with the FirebaseUI for two tenants which have different sets of identity providers enabled.

Customizing FirebaseUI for authentication

Currently, FirebaseUI does not offer customization out of the box. However, the HTML around the widget is not affected by it so you can display everything you want around the widget container.

Advanced

FirebaseUI widget modes

Upon initialization, FirebaseUI will look for the mode parameter in the URL. Depending on the value of this parameter, it will trigger a specific mode. When no mode parameter is found, it will default to the sign-in mode.

You can change the name of this parameter with the queryParameterForWidgetMode configuration parameter.

Query parameter valueDescription
?mode=selectSign-in mode

Example:

https://<url-of-the-widget>?mode=select

Overwriting the sign-in success URL

You can pass a query parameter to the widget's URL that will overwrite the URL the user is redirected to after a successful sign-in. If you do so, you must set the configuration signInSuccessUrl value (even if it will be overwritten). When passing the redirect URL this way, the signInSuccessWithAuthResult callback will receive the value as the redirectUrl argument.

You must include the mode explicitly in the URL when using the signInSuccessUrl parameter, otherwise FirebaseUI will directly redirect to the URL specified.

You can change the name of this parameter with the queryParameterForSignInSuccessUrl configuration parameter.

Example:

https://<url-of-the-widget>?mode=select&signInSuccessUrl=signedIn.html will redirect the user to https://<url-of-the-widget>/signedIn.html after a successful sign-in flow.

Developer Setup

Dependencies

To set up a development environment to build FirebaseUI from source, you must have the following installed:

  • Node.js (>= 6.0.0)
  • npm (should be included with Node.js)
  • Java SE Runtime Environment 8

In order to run the demo and tests, you must also have:

  • Python (2.7)

Download the FirebaseUI source and its dependencies with:

git clone https://github.com/firebase/firebaseui-web.git
cd firebaseui-web
npm install

Building FirebaseUI

To build the library, run:

npm run build

This will create output files in the dist/ folder.

To build a localized JavaScript binary, run:

npm run build build-js-{LANGUAGE_CODE}

where {LANGUAGE_CODE} is replaced by the code of the language you want. For example, the French binary can be built with npm run build build-js-fr. This will create a binary firebaseui__fr.js in the dist/ folder.

Build names for language codes with underscores, eg. zh_tw, zh_cn, pt_pt will be mapped to zh-TW, xh-CN, pt-PT. The underscore will be replaced by a hyphen symbol and the subsequent characters will be capitalized.

npm run build build-js-zh-TW

This will create a binary firebaseui__zh_tw.js in the dist/ folder.

To build a localized npm FirebaseUI module, run:

npm run build build-npm-{LANGUAGE_CODE}

Make sure all underscore symbols in the LANGUAGE_CODE are replaced with dashes. This will generate dist/npm__{LANGUAGE_CODE}.js. You can then import/require it:

import firebaseui from './npm__{LANGUAGE_CODE}';

Build names for language codes with underscores, eg. zh_tw, zh_cn, pt_pt will be mapped to zh-TW, xh-CN, pt-PT. The underscore will be replaced by a hyphen symbol and the subsequent characters will be capitalized.

npm run build build-npm-zh-TW

This will create a binary npm__zh_tw.js in the dist/ folder.

Running the demo app

To run the demo app, you must have a Firebase project set up on the Firebase Console. Copy demo/public/sample-config.js to demo/public/config.js:

cp demo/public/sample-config.js demo/public/config.js

Copy the data from the "Add Firebase to your web app" flow in Firebase Console. Next, run:

npm run demo

This will start a local server serving a FirebaseUI demo app with all local changes. More details can be found in the demo app folder, covering how to configure the app to be deployed on a Firebase Hosting instance.

Running unit tests.

All unit tests can be run on the command line (via PhantomJS) with:

npm test

Alternatively, the unit tests can be run manually by running:

npm run serve

Then, all unit tests can be run at: http://localhost:4000/buildtools/alltests.html You can also run tests individually by accessing each HTML file under generated/tests, for example: http://localhost:4000/generated/tests/javascript/widgets/authuitest.html

Run tests using SauceLabs

You need a SauceLabs account to run tests on SauceLabs.

Go to your SauceLab account, under "My Account", and copy paste the access key. Now export the following variables, in two Terminal windows:

export SAUCE_USERNAME=<your username>
export SAUCE_ACCESS_KEY=<the copy pasted access key>

Then, in one Terminal window, start SauceConnect:

./buildtools/sauce_connect.sh

Take note of the "Tunnel Identifier" value logged in the terminal,at the top. In the other terminal that has the exported variables, run the tests:

npm test -- --saucelabs --tunnelIdentifier=<the tunnel identifier>

IAP External Identities Support with FirebaseUI

You can use FirebaseUI to build the authentication page to use external identities with Google Cloud IAP. The documentation can be found here.

Cordova Setup

Introduction

FirebaseUI sign-in widget supports Cordova applications. This includes email/password and all OAuth providers (Google, Facebook, Twitter and GitHub). Phone authentication is not supported due to the limitation in the underlying Firebase core SDK. Email link authentication is not yet supported due to the inability to detect the incoming link when the user clicks it to complete sign-in.

Available providers

ProviderValue
Googlefirebase.auth.GoogleAuthProvider.PROVIDER_ID
Facebookfirebase.auth.FacebookAuthProvider.PROVIDER_ID
Twitterfirebase.auth.TwitterAuthProvider.PROVIDER_ID
Githubfirebase.auth.GithubAuthProvider.PROVIDER_ID
Email and passwordfirebase.auth.EmailAuthProvider.PROVIDER_ID
Anonymousfirebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
Microsoftmicrosoft.com
Yahooyahoo.com
SAML (GCIP only)saml.*********
OIDC (GCIP only)oidc.*********

Setup and Usage

In order to integrate FirebaseUI with your Cordova application, you need to follow these steps:

  • Install the necessary Cordova plugins, make the necessary Firebase Console changes and update your config.xml file as documented in OAuth Sign-In for Cordova
  • After you have successfully configured your application, you can use FirebaseUI in your Cordova application just like any other traditional browser applications.

Keep in mind the following while you set up the app:

  • Only redirect signInFlow is supported as Firebase Auth does not support popup mode for Cordova.
  • firebase.auth.PhoneAuthProvider.PROVIDER_ID is not currently supported.
  • As the application runs within an embedded webview, accountchooser.com will always be disabled.
  • If you are providing a Content-Security-Policy make sure you add the appropriate exceptions for FirebaseUI resources (style-src, media-src, img-src, script-src, etc.) and underlying Firebase JS SDK.

React DOM Setup

In React DOM applications you can use the [FirebaseUI

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文