Firebase Authentication with Identity Platform にアップグレードした場合は、SMS 多要素認証をウェブアプリに追加できます。
多要素認証により、アプリのセキュリティが向上します。攻撃者はパスワードやソーシャル アカウントを侵害することがよくありますが、テキスト メッセージを傍受することはより困難です。
あなたが始める前に
多要素認証をサポートするプロバイダーを少なくとも 1 つ有効にします。電話認証、匿名認証、Apple Game Centerを除くすべてのプロバイダーが MFA をサポートしています。
アプリがユーザーのメールを確認していることを確認してください。 MFA にはメール認証が必要です。これにより、悪意のあるアクターが所有していない電子メールでサービスに登録し、2 番目の要素を追加して実際の所有者をロックアウトすることを防ぎます。
マルチテナンシーの使用
マルチテナント環境で使用するために多要素認証を有効にする場合は、(このドキュメントの残りの手順に加えて) 次の手順を完了してください。
GCP Console で、操作するテナントを選択します。
コードで、
Auth
インスタンスのtenantId
フィールドをテナントの ID に設定します。例えば:Web version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";
Web version 8
firebase.auth().tenantId = 'myTenantId1';
多要素認証の有効化
Firebase コンソールの[認証] > [サインイン方法] ページを開きます。
[詳細]セクションで、 SMS 多要素認証を有効にします。
アプリのテストに使用する電話番号も入力する必要があります。オプションですが、開発中のスロットリングを避けるために、テスト電話番号を登録することを強くお勧めします。
アプリのドメインをまだ承認していない場合は、Firebase コンソールの[認証] > [設定]ページで許可リストに追加します。
登録パターンの選択
アプリが多要素認証を必要とするかどうか、ユーザーを登録する方法と時期を選択できます。いくつかの一般的なパターンは次のとおりです。
ユーザーの第 2 要素を登録の一部として登録します。アプリですべてのユーザーに対して多要素認証が必要な場合は、この方法を使用します。
登録時に第 2 要素を登録するためのスキップ可能なオプションを提供します。多要素認証を推奨するが必須ではないアプリは、このアプローチを好む可能性があります。
サインアップ画面ではなく、ユーザーのアカウントまたはプロファイル管理ページから 2 番目の要素を追加する機能を提供します。これにより、登録プロセス中の摩擦を最小限に抑えながら、セキュリティに敏感なユーザーが多要素認証を利用できるようにします.
ユーザーがセキュリティ要件の高い機能にアクセスしたい場合は、第 2 要素を段階的に追加する必要があります。
reCAPTCHA ベリファイアの設定
SMS コードを送信する前に、reCAPTCHA ベリファイアを構成する必要があります。 Firebase は reCAPTCHA を使用して、電話番号の確認リクエストがアプリの許可されたドメインのいずれかから送信されるようにすることで、不正使用を防ぎます。
reCAPTCHA クライアントを手動で設定する必要はありません。クライアント SDK のRecaptchaVerifier
オブジェクトは、必要なクライアント キーとシークレットを自動的に作成して初期化します。
目に見えない reCAPTCHA の使用
RecaptchaVerifier
オブジェクトは、目に見えない reCAPTCHAをサポートしています。これにより、多くの場合、操作を必要とせずにユーザーを検証できます。非表示の reCAPTCHA を使用するには、 size
パラメーターをinvisible
に設定してRecaptchaVerifier
を作成し、多要素登録を開始する UI 要素の ID を指定します。
Web version 9
import { RecaptchaVerifier } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier("sign-in-button", {
"size": "invisible",
"callback": function(response) {
// reCAPTCHA solved, you can proceed with
// phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
}
}, auth);
Web version 8
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
}
});
reCAPTCHA ウィジェットの使用
可視の reCAPTCHA ウィジェットを使用するには、ウィジェットを含む HTML 要素を作成してから、UI コンテナーの ID を使用してRecaptchaVerifier
オブジェクトを作成します。オプションで、reCAPTCHA が解決または期限切れになったときに呼び出されるコールバックを設定することもできます。
Web version 9
import { RecaptchaVerifier } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(
"recaptcha-container",
// Optional reCAPTCHA parameters.
{
"size": "normal",
"callback": function(response) {
// reCAPTCHA solved, you can proceed with
// phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
},
"expired-callback": function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
}, auth
);
Web version 8
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
'recaptcha-container',
// Optional reCAPTCHA parameters.
{
'size': 'normal',
'callback': function(response) {
// reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
// ...
onSolvedRecaptcha();
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
reCAPTCHA の事前レンダリング
必要に応じて、2 要素登録を開始する前に reCAPTCHA を事前にレンダリングできます。
Web version 9
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web version 8
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
render()
が解決された後、reCAPTCHA のウィジェット ID を取得します。これを使用してreCAPTCHA APIを呼び出すことができます。
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier は、 verifyメソッドを使用してこのロジックを抽象化するため、 grecaptcha
変数を直接処理する必要はありません。
第 2 要素の登録
ユーザーの新しい第 2 要素を登録するには:
ユーザーを再認証します。
ユーザーに電話番号を入力してもらいます。
前のセクションで説明したように、reCAPTCHA ベリファイアを初期化します。 RecaptchaVerifier インスタンスがすでに構成されている場合は、この手順をスキップします。
Web version 9
import { RecaptchaVerifier } from "firebase/auth"; const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
Web version 8
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
ユーザーの多要素セッションを取得します。
Web version 9
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });
Web version 8
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })
ユーザーの電話番号と多要素セッションで
PhoneInfoOptions
オブジェクトを初期化します。Web version 9
// Specify the phone number and pass the MFA session. const phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };
Web version 8
// Specify the phone number and pass the MFA session. var phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };
ユーザーの電話に確認メッセージを送信します。
Web version 9
import { PhoneAuthProvider } from "firebase/auth"; const phoneAuthProvider = new PhoneAuthProvider(auth); phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function (verificationId) { // verificationId will be needed to complete enrollment. });
Web version 8
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider(); // Send SMS verification code. return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function(verificationId) { // verificationId will be needed for enrollment completion. })
必須ではありませんが、SMS メッセージを受信することと、標準料金が適用されることを事前にユーザーに通知することをお勧めします。
リクエストが失敗した場合は、reCAPTCHA をリセットしてから、前の手順を繰り返して、ユーザーが再試行できるようにします。 reCAPTCHA トークンは 1 回しか使用できないため、
verifyPhoneNumber()
はエラーをスローすると reCAPTCHA を自動的にリセットすることに注意してください。Web version 9
recaptchaVerifier.clear();
Web version 8
recaptchaVerifier.clear();
SMS コードが送信されたら、ユーザーにコードを確認するように依頼します。
Web version 9
// Ask user for the verification code. Then: const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
Web version 8
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
PhoneAuthCredential
でMultiFactorAssertion
オブジェクトを初期化します。Web version 9
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web version 8
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
登録を完了します。必要に応じて、2 番目の要素の表示名を指定できます。これは、認証フロー中に電話番号がマスクされるため (+1******1234 など)、複数の第 2 要素を持つユーザーに役立ちます。
Web version 9
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");
Web version 8
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
以下のコードは、2 番目の要素を登録する完全な例を示しています。
Web version 9
import {
multiFactor, PhoneAuthProvider, PhoneMultiFactorGenerator,
RecaptchaVerifier
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
multiFactor(user).getSession()
.then(function (multiFactorSession) {
// Specify the phone number and pass the MFA session.
const phoneInfoOptions = {
phoneNumber: phoneNumber,
session: multiFactorSession
};
const phoneAuthProvider = new PhoneAuthProvider(auth);
// Send SMS verification code.
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier);
}).then(function (verificationId) {
// Ask user for the verification code. Then:
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
// Complete enrollment.
return multiFactor(user).enroll(multiFactorAssertion, mfaDisplayName);
});
Web version 8
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
user.multiFactor.getSession().then(function(multiFactorSession) {
// Specify the phone number and pass the MFA session.
var phoneInfoOptions = {
phoneNumber: phoneNumber,
session: multiFactorSession
};
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
// Send SMS verification code.
return phoneAuthProvider.verifyPhoneNumber(
phoneInfoOptions, recaptchaVerifier);
})
.then(function(verificationId) {
// Ask user for the verification code.
var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
// Complete enrollment.
return user.multiFactor.enroll(multiFactorAssertion, mfaDisplayName);
});
おめでとう!ユーザーの 2 番目の認証要素が正常に登録されました。
第 2 要素によるユーザーのサインイン
2 要素 SMS 検証を使用してユーザーをサインインするには:
最初の要素でユーザーをサインインさせてから、
auth/multi-factor-auth-required
エラーをキャッチします。このエラーには、リゾルバー、登録された第 2 要素に関するヒント、およびユーザーが第 1 要素で正常に認証されたことを証明する基になるセッションが含まれています。たとえば、ユーザーの最初の要素が電子メールとパスワードである場合:
Web version 9
import { getAuth, getMultiFactorResolver} from "firebase/auth"; const auth = getAuth(); signInWithEmailAndPassword(auth, email, password) .then(function (userCredential) { // User successfully signed in and is not enrolled with a second factor. }) .catch(function (error) { if (error.code == 'auth/multi-factor-auth-required') { // The user is a multi-factor user. Second factor challenge is required. resolver = getMultiFactorResolver(auth, error); // ... } else if (error.code == 'auth/wrong-password') { // Handle other errors such as wrong password. } });
Web version 8
firebase.auth().signInWithEmailAndPassword(email, password) .then(function(userCredential) { // User successfully signed in and is not enrolled with a second factor. }) .catch(function(error) { if (error.code == 'auth/multi-factor-auth-required') { // The user is a multi-factor user. Second factor challenge is required. resolver = error.resolver; // ... } else if (error.code == 'auth/wrong-password') { // Handle other errors such as wrong password. } ... });
ユーザーの最初の要素が OAuth、SAML、OIDC などのフェデレーション プロバイダーである場合は、
signInWithPopup()
またはsignInWithRedirect()
) を呼び出した後にエラーをキャッチします。ユーザーが複数の第 2 要素を登録している場合は、どれを使用するか尋ねます。
Web version 9
// Ask user which second factor to use. // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber // You can get the display name via resolver.hints[selectedIndex].displayName if (resolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID) { // User selected a phone second factor. // ... } else { // Unsupported second factor. // Note that only phone second factors are currently supported. }
Web version 8
// Ask user which second factor to use. // You can get the masked phone number via resolver.hints[selectedIndex].phoneNumber // You can get the display name via resolver.hints[selectedIndex].displayName if (resolver.hints[selectedIndex].factorId === firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) { // User selected a phone second factor. // ... } else { // Unsupported second factor. // Note that only phone second factors are currently supported. }
前のセクションで説明したように、reCAPTCHA ベリファイアを初期化します。 RecaptchaVerifier インスタンスがすでに構成されている場合は、この手順をスキップします。
Web version 9
import { RecaptchaVerifier } from "firebase/auth"; recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
Web version 8
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
ユーザーの電話番号と多要素セッションで
PhoneInfoOptions
オブジェクトを初期化します。これらの値は、auth/multi-factor-auth-required
エラーに渡されるresolver
オブジェクトに含まれています。Web version 9
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };
Web version 8
var phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };
ユーザーの電話に確認メッセージを送信します。
Web version 9
// Send SMS verification code. const phoneAuthProvider = new PhoneAuthProvider(auth); phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function (verificationId) { // verificationId will be needed for sign-in completion. });
Web version 8
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider(); // Send SMS verification code. return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier) .then(function(verificationId) { // verificationId will be needed for sign-in completion. })
リクエストが失敗した場合は、reCAPTCHA をリセットしてから、前の手順を繰り返して、ユーザーが再試行できるようにします。
Web version 9
recaptchaVerifier.clear();
Web version 8
recaptchaVerifier.clear();
SMS コードが送信されたら、ユーザーにコードを確認するように依頼します。
Web version 9
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
Web version 8
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
PhoneAuthCredential
でMultiFactorAssertion
オブジェクトを初期化します。Web version 9
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web version 8
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
resolver.resolveSignIn()
を呼び出して、2 次認証を完了します。その後、標準のプロバイダー固有のデータと認証資格情報を含む元のサインイン結果にアクセスできます。Web version 9
// Complete sign-in. This will also trigger the Auth state listeners. resolver.resolveSignIn(multiFactorAssertion) .then(function (userCredential) { // userCredential will also contain the user, additionalUserInfo, optional // credential (null for email/password) associated with the first factor sign-in. // For example, if the user signed in with Google as a first factor, // userCredential.additionalUserInfo will contain data related to Google // provider that the user signed in with. // - user.credential contains the Google OAuth credential. // - user.credential.accessToken contains the Google OAuth access token. // - user.credential.idToken contains the Google OAuth ID token. });
Web version 8
// Complete sign-in. This will also trigger the Auth state listeners. resolver.resolveSignIn(multiFactorAssertion) .then(function(userCredential) { // userCredential will also contain the user, additionalUserInfo, optional // credential (null for email/password) associated with the first factor sign-in. // For example, if the user signed in with Google as a first factor, // userCredential.additionalUserInfo will contain data related to Google provider that // the user signed in with. // user.credential contains the Google OAuth credential. // user.credential.accessToken contains the Google OAuth access token. // user.credential.idToken contains the Google OAuth ID token. });
以下のコードは、多要素ユーザーのサインインの完全な例を示しています。
Web version 9
import {
getAuth,
getMultiFactorResolver,
PhoneAuthProvider,
PhoneMultiFactorGenerator,
RecaptchaVerifier,
signInWithEmailAndPassword
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
.then(function (userCredential) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
})
.catch(function (error) {
if (error.code == 'auth/multi-factor-auth-required') {
const resolver = getMultiFactorResolver(auth, error);
// Ask user which second factor to use.
if (resolver.hints[selectedIndex].factorId ===
PhoneMultiFactorGenerator.FACTOR_ID) {
const phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};
const phoneAuthProvider = new PhoneAuthProvider(auth);
// Send SMS verification code
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
.then(function (verificationId) {
// Ask user for the SMS verification code. Then:
const cred = PhoneAuthProvider.credential(
verificationId, verificationCode);
const multiFactorAssertion =
PhoneMultiFactorGenerator.assertion(cred);
// Complete sign-in.
return resolver.resolveSignIn(multiFactorAssertion)
})
.then(function (userCredential) {
// User successfully signed in with the second factor phone number.
});
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
}
});
Web version 8
var resolver;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(userCredential) {
// User is not enrolled with a second factor and is successfully signed in.
// ...
})
.catch(function(error) {
if (error.code == 'auth/multi-factor-auth-required') {
resolver = error.resolver;
// Ask user which second factor to use.
if (resolver.hints[selectedIndex].factorId ===
firebase.auth.PhoneMultiFactorGenerator.FACTOR_ID) {
var phoneInfoOptions = {
multiFactorHint: resolver.hints[selectedIndex],
session: resolver.session
};
var phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
// Send SMS verification code
return phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions, recaptchaVerifier)
.then(function(verificationId) {
// Ask user for the SMS verification code.
var cred = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
var multiFactorAssertion =
firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
// Complete sign-in.
return resolver.resolveSignIn(multiFactorAssertion)
})
.then(function(userCredential) {
// User successfully signed in with the second factor phone number.
});
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
} ...
});
おめでとう!多要素認証を使用してユーザーのサインインに成功しました。
次は何ですか
- Admin SDK を使用して、多要素ユーザーをプログラムで管理します。