FirebaseUIは、アプリで使用するためのドロップイン UI フローを提供する Firebase Authentication SDK の上に構築されたライブラリです。 FirebaseUI には次の利点があります。
- 複数のプロバイダー- メール/パスワード、メール リンク、電話認証、Google、Facebook、Twitter、GitHub サインインのサインイン フロー。
- アカウントのリンク- ID プロバイダー間でユーザー アカウントを安全にリンクするためのフロー。
- カスタマイズ- アプリの要件に合わせて FirebaseUI の CSS スタイルをオーバーライドします。また、FirebaseUI はオープン ソースであるため、プロジェクトをフォークして、必要に応じて正確にカスタマイズできます。
- ワンタップ サインアップと自動サインイン- ワンタップ サインアップとの自動統合により、デバイスを問わずすばやくサインインできます。
- ローカライズされた UI - 40 を超える言語の国際化。
- 匿名ユーザーのアップグレード- サインイン/サインアップによって匿名ユーザーをアップグレードする機能。詳細については、匿名ユーザーのアップグレード セクションを参照してください。
あなたが始める前に
Firebase Authentication をウェブ アプリケーションに追加し、v9 互換 (推奨) または古い SDK (上のサイドバーを参照) を使用していることを確認します。
次のいずれかのオプションを使用して FirebaseUI を含めます。
CDN
Firebase コンソールの初期化スニペットの下にある、ページの <head> タグに次のスクリプトと CSS ファイルを含めます。
<script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script> <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
npm モジュール
次のコマンドを使用して、npm 経由で FirebaseUI とその依存関係をインストールします。
$ npm install firebaseui --save
ソース ファイル内に次のモジュール
require
です。var firebase = require('firebase'); var firebaseui = require('firebaseui');
バウアー コンポーネント
次のコマンドを使用して、Bower 経由で FirebaseUI とその依存関係をインストールします。
$ bower install firebaseui --save
HTTP サーバーが
bower_components/
内のファイルを提供する場合は、HTML に必要なファイルを含めます。<script src="bower_components/firebaseui/dist/firebaseui.js"></script> <link type="text/css" rel="stylesheet" href="bower_components/firebaseui/dist/firebaseui.css" />
FirebaseUI の初期化
SDK をインポートしたら、Auth UI を初期化します。
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
サインイン方法を設定する
Firebase を使用してユーザーをサインインさせる前に、サポートするサインイン方法を有効にして構成する必要があります。
メールアドレスとパスワード
Firebase コンソールで、[認証]セクションを開き、メールとパスワードの認証を有効にします。
メール プロバイダー ID を FirebaseUI
signInOptions
のリストに追加します。ui.start('#firebaseui-auth-container', { signInOptions: [ firebase.auth.EmailAuthProvider.PROVIDER_ID ], // Other config options... });
オプション:
EmailAuthProvider
は、ユーザーに表示名の入力を要求するように構成できます (デフォルトはtrue
)。ui.start('#firebaseui-auth-container', { signInOptions: [ { provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, requireDisplayName: false } ] });
メールリンク認証
Firebase コンソールで、[認証]セクションを開きます。 [サインイン方法] タブで、電子メール/パスワードプロバイダーを有効にします。メール リンク サインインを使用するには、メール/パスワード サインインを有効にする必要があることに注意してください。
同じセクションで、[電子メール リンク (パスワードなしのサインイン) ] サインイン方法を有効にし、[保存] をクリックします。
電子メール プロバイダー ID を FirebaseUI
signInOptions
のリストに追加し、電子メール リンクsignInMethod
を追加します。ui.start('#firebaseui-auth-container', { signInOptions: [ { provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD } ], // Other config options... });
サインイン UI を条件付きでレンダリングする場合 (単一ページ アプリに関連)、
ui.isPendingRedirect()
を使用して、URL が電子メール リンクを使用したサインインに対応しており、サインインを完了するために UI をレンダリングする必要があるかどうかを検出します。// Is there an email link sign-in? if (ui.isPendingRedirect()) { ui.start('#firebaseui-auth-container', uiConfig); } // This can also be done via: if (firebase.auth().isSignInWithEmailLink(window.location.href)) { ui.start('#firebaseui-auth-container', uiConfig); }
オプション: メール リンク サインイン用の
EmailAuthProvider
は、ユーザーがクロス デバイス サインインを完了することを許可またはブロックするように構成できます。オプションの
emailLinkSignIn
コールバックを定義して、リンクを送信するときに使用するfirebase.auth.ActionCodeSettings
構成を返すことができます。これにより、リンクの処理方法、カスタム ダイナミック リンク、ディープ リンクの追加状態などを指定する機能が提供されます。指定されていない場合は、現在の URL が使用され、Web のみのフローがトリガーされます。FirebaseUI-web での電子メール リンク サインインは、 FirebaseUI-AndroidおよびFirebaseUI-iOSと互換性があり、FirebaseUI-Android からフローを開始する 1 人のユーザーがリンクを開いて、FirebaseUI-web でのサインインを完了することができます。逆の流れも同様です。
ui.start('#firebaseui-auth-container', { signInOptions: [ { provider: firebase.auth.EmailAuthProvider.PROVIDER_ID, signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD, // Allow the user the ability to complete sign-in cross device, // including the mobile apps specified in the ActionCodeSettings // object below. forceSameDevice: false, // Used to define the optional firebase.auth.ActionCodeSettings if // additional state needs to be passed along request and whether to open // the link in a mobile app if it is installed. emailLinkSignIn: function() { return { // Additional state showPromo=1234 can be retrieved from URL on // sign-in completion in signInSuccess callback by checking // window.location.href. url: 'https://www.example.com/completeSignIn?showPromo=1234', // Custom FDL domain. dynamicLinkDomain: 'example.page.link', // Always true for email link sign-in. handleCodeInApp: true, // Whether to handle link in iOS app if installed. iOS: { bundleId: 'com.example.ios' }, // Whether to handle link in Android app if opened in an Android // device. android: { packageName: 'com.example.android', installApp: true, minimumVersion: '12' } }; } } ] });
OAuth プロバイダー (Google、Facebook、Twitter、GitHub)
Firebase コンソールで、[認証]セクションを開き、指定された OAuth プロバイダーのサインインを有効にします。対応する OAuth クライアント ID とシークレットも指定されていることを確認してください。
また、[認証]セクションで、サインイン ページが表示されるドメインも承認済みドメイン リストに追加されていることを確認します。
OAuth プロバイダー ID を FirebaseUI
signInOptions
のリストに追加します。ui.start('#firebaseui-auth-container', { signInOptions: [ // List of OAuth providers supported. firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.FacebookAuthProvider.PROVIDER_ID, firebase.auth.TwitterAuthProvider.PROVIDER_ID, firebase.auth.GithubAuthProvider.PROVIDER_ID ], // Other config options... });
オプション: カスタム スコープまたはプロバイダーごとのカスタム 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. ] });
電話番号
Firebase コンソールで [認証]セクションを開き、電話番号によるサインインを有効にします。
サインイン ページが表示されるドメインも、承認済みドメイン リストに追加されていることを確認してください。
電話番号プロバイダー ID を FirebaseUI
signInOptions
のリストに追加します。ui.start('#firebaseui-auth-container', { signInOptions: [ firebase.auth.PhoneAuthProvider.PROVIDER_ID ], // Other config options... });
オプション: PhoneAuthProvider は、reCAPTCHA が表示されているかどうかにかかわらず、カスタム reCAPTCHA パラメーターを使用して構成できます (デフォルトは通常)。詳細については、 reCAPTCHA API ドキュメントを参照してください。
電話番号入力で選択するデフォルトの国も設定できます。コードの完全なリストについては、サポートされている国コードのリストを参照してください。指定しない場合、電話番号の入力はデフォルトで米国 (+1) になります。
現在、次のオプションがサポートされています。
ui.start('#firebaseui-auth-container', { signInOptions: [ { provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID, recaptchaParameters: { type: 'image', // 'audio' size: 'normal', // 'invisible' or 'compact' badge: 'bottomleft' //' bottomright' or 'inline' applies to invisible. }, defaultCountry: 'GB', // Set default country to the United Kingdom (+44). // For prefilling the national number, set defaultNationNumber. // This will only be observed if only phone Auth provider is used since // for multiple providers, the NASCAR screen will always render first // with a 'sign in with phone number' button. defaultNationalNumber: '1234567890', // You can also pass the full phone number string instead of the // 'defaultCountry' and 'defaultNationalNumber'. However, in this case, // the first country ID that matches the country code will be used to // populate the country selector. So for countries that share the same // country code, the selected country may not be the expected one. // In that case, pass the 'defaultCountry' instead to ensure the exact // country is selected. The 'defaultCountry' and 'defaultNationaNumber' // will always have higher priority than 'loginHint' which will be ignored // in their favor. In this case, the default country will be 'GB' even // though 'loginHint' specified the country code as '+1'. loginHint: '+11234567890' } ] });
ログイン
FirebaseUI サインイン フローを開始するには、基礎となるAuth
インスタンスを渡して FirebaseUI インスタンスを初期化します。
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
FirebaseUI ログイン ウィジェットがレンダリングされる HTML 要素を定義します。
<!-- The surrounding HTML is left untouched by FirebaseUI.
Your app may use that space for branding, controls and other customizations.-->
<h1>Welcome to My Awesome App</h1>
<div id="firebaseui-auth-container"></div>
<div id="loader">Loading...</div>
FirebaseUI 構成を指定します (サポートされているプロバイダー、UI のカスタマイズ、成功のコールバックなど)。
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
// User successfully signed in.
// Return type determines whether we continue the redirect automatically
// or whether we leave that to developer to handle.
return true;
},
uiShown: function() {
// The widget is rendered.
// Hide the loader.
document.getElementById('loader').style.display = 'none';
}
},
// Will use popup for IDP Providers sign-in flow instead of the default, redirect.
signInFlow: 'popup',
signInSuccessUrl: '<url-to-redirect-to-on-success>',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
firebase.auth.PhoneAuthProvider.PROVIDER_ID
],
// Terms of service url.
tosUrl: '<your-tos-url>',
// Privacy policy url.
privacyPolicyUrl: '<your-privacy-policy-url>'
};
最後に、FirebaseUI Auth インターフェースをレンダリングします。
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
匿名ユーザーのアップグレード
匿名ユーザーのアップグレードを有効にする
匿名ユーザーが永続的なアカウントでサインインまたはサインアップする場合、ユーザーがサインアップする前に行っていたことを続行できることを確認する必要があります。これを行うには、サインイン UI を構成するときにautoUpgradeAnonymousUsers
をtrue
に設定するだけです (このオプションは既定で無効になっています)。
匿名ユーザーのアップグレード マージの競合の処理
最初に匿名でサインインしたユーザーが、既存の Firebase ユーザーにアップグレードしようとする場合があります。既存のユーザーを別の既存のユーザーにリンクすることはできないため、上記の状況が発生すると、FirebaseUI はエラー コード firebaseui firebaseui/anonymous-upgrade-merge-conflict
でsignInFailure
コールバックをトリガーします。エラー オブジェクトには、永続的な資格情報も含まれます。サインインを完了するには、永久認証情報を使用したサインインをコールバックでトリガーする必要があります。 auth.signInWithCredential(error.credential)
を使用してサインインを完了する前に、匿名ユーザーのデータを保存し、匿名ユーザーを削除する必要があります。次に、サインインが完了したら、データを非匿名ユーザーにコピーします。以下の例は、このフローがどのように機能するかを示しています。
// Temp variable to hold the anonymous user data if needed.
var data = null;
// Hold a reference to the anonymous current user.
var anonymousUser = firebase.auth().currentUser;
ui.start('#firebaseui-auth-container', {
// Whether to upgrade anonymous users should be explicitly provided.
// The user must already be signed in anonymously before FirebaseUI is
// rendered.
autoUpgradeAnonymousUsers: true,
signInSuccessUrl: '<url-to-redirect-to-on-success>',
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
firebase.auth.PhoneAuthProvider.PROVIDER_ID
],
callbacks: {
// signInFailure callback must be provided to handle merge conflicts which
// occur when an existing credential is linked to an anonymous user.
signInFailure: function(error) {
// For merge conflicts, the error.code will be
// 'firebaseui/anonymous-upgrade-merge-conflict'.
if (error.code != 'firebaseui/anonymous-upgrade-merge-conflict') {
return Promise.resolve();
}
// The credential the user tried to sign in with.
var cred = error.credential;
// Copy data from anonymous user to permanent user and delete anonymous
// user.
// ...
// Finish sign-in after data is copied.
return firebase.auth().signInWithCredential(cred);
}
}
});
次のステップ
- FirebaseUI の使用とカスタマイズの詳細については、 READMEにアクセスしてください。
- FirebaseUI で問題を見つけて報告したい場合は、 GitHub イシュー トラッカーを使用してください。