如果您已升級至使用 Identity Platform 的 Firebase 驗證,則可以將 SMS 多重驗證新增至您的 Web 應用程式中。
多重身份驗證可提高應用程式的安全性。雖然攻擊者經常破壞密碼和社交帳戶,但攔截簡訊卻更加困難。
在你開始之前
啟用至少一個支援多重身份驗證的提供者。每個提供者都支援 MFA,電話身份驗證、匿名身份驗證和 Apple Game Center除外。
確保您的應用程式正在驗證使用者電子郵件。 MFA 需要電子郵件驗證。這可以防止惡意行為者使用不屬於他們的電子郵件註冊服務,然後透過添加第二個因素來鎖定真正的所有者。
使用多租戶
如果您要在多租用戶環境中啟用多重身份驗證,請確保完成以下步驟(除了本文檔中的其餘說明之外):
在 GCP Console 中,選擇您想要使用的租用戶。
在您的程式碼中,將
Auth
實例上的tenantId
欄位設定為租用戶的ID。例如:網路模組化API
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";
Web 命名空間 API
firebase.auth().tenantId = 'myTenantId1';
啟用多重身份驗證
開啟 Firebase 控制台的驗證 > 登入方法頁面。
在「進階」部分中,啟用簡訊多重身份驗證。
您還應該輸入用於測試應用程式的電話號碼。雖然可選,但強烈建議註冊測試電話號碼,以避免開發過程中受到限制。
如果您尚未授權套用的網域,請將其新增至 Firebase 控制台的「驗證」>「設定」頁面上的允許清單中。
選擇註冊模式
您可以選擇應用程式是否需要多重身份驗證,以及註冊用戶的方式和時間。一些常見的模式包括:
將使用者的第二個因素註冊為註冊的一部分。如果您的應用程式需要對所有使用者進行多重身份驗證,請使用此方法。
提供可跳過的選項以在註冊過程中註冊第二個因素。想要鼓勵但不要求多因素身份驗證的應用程式可能會更喜歡這種方法。
提供從使用者帳戶或個人資料管理頁面(而非註冊畫面)新增第二個因素的功能。這最大限度地減少了註冊過程中的摩擦,同時仍為安全敏感的用戶提供多因素身份驗證。
當使用者想要存取安全要求更高的功能時,需要逐步加入第二個因素。
設定 reCAPTCHA 驗證器
在傳送簡訊代碼之前,您需要設定 reCAPTCHA 驗證程式。 Firebase 使用 reCAPTCHA 確保電話號碼驗證請求來自應用程式允許的網域之一,以防止濫用。
您無需手動設定 reCAPTCHA 用戶端;客戶端 SDK 的RecaptchaVerifier
物件會自動建立並初始化任何必要的客戶端金鑰和機密。
使用不可見的 reCAPTCHA
RecaptchaVerifier
物件支援不可見的 reCAPTCHA ,它通常可以驗證使用者而不需要任何互動。若要使用不可見的 reCAPTCHA,請建立一個RecaptchaVerifier
,並將size
參數設為invisible
,並指定啟動多重註冊的 UI 元素的 ID:
網路模組化API
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 命名空間 API
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 解決或過期時呼叫的回呼:
網路模組化API
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 命名空間 API
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
或者,您可以在開始兩因素註冊之前預呈現 reCAPTCHA:
網路模組化API
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web 命名空間 API
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
render()
解析後,您將獲得 reCAPTCHA 的小工具 ID,您可以使用它來呼叫reCAPTCHA API :
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier 使用verify方法抽象化了此邏輯,因此您無需直接處理grecaptcha
變數。
註冊第二個因素
若要為用戶註冊新的次要因素:
重新驗證使用者身份。
要求使用者輸入他們的電話號碼。
如上一節所示初始化 reCAPTCHA 驗證器。如果已設定 RecaptchaVerifier 實例,請跳過此步驟:
網路模組化API
import { RecaptchaVerifier } from "firebase/auth"; const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
Web 命名空間 API
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
為用戶獲取多因素會話:
網路模組化API
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });
Web 命名空間 API
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })
使用使用者的電話號碼和多因素會話初始化
PhoneInfoOptions
物件:網路模組化API
// Specify the phone number and pass the MFA session. const phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };
Web 命名空間 API
// Specify the phone number and pass the MFA session. var phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };
向用戶手機發送驗證簡訊:
網路模組化API
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 命名空間 API
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. })
雖然不是必需的,但最佳做法是提前通知用戶他們將收到短信,並且適用標準費率。
如果請求失敗,請重設 reCAPTCHA,然後重複上一步,以便使用者可以重試。請注意,
verifyPhoneNumber()
在引發錯誤時將自動重置 reCAPTCHA,因為 reCAPTCHA 令牌只能使用一次。網路模組化API
recaptchaVerifier.clear();
Web 命名空間 API
recaptchaVerifier.clear();
發送簡訊代碼後,請用戶驗證該代碼:
網路模組化API
// Ask user for the verification code. Then: const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
Web 命名空間 API
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
使用
PhoneAuthCredential
初始化MultiFactorAssertion
物件:網路模組化API
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web 命名空間 API
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
完成報名。或者,您可以指定第二個因素的顯示名稱。這對於具有多個第二因素的使用者非常有用,因為電話號碼在身份驗證流程中被封鎖(例如,+1*****1234)。
網路模組化API
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");
Web 命名空間 API
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
下面的程式碼顯示了註冊第二個因素的完整範例:
網路模組化API
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 命名空間 API
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);
});
恭喜!您已成功為使用者註冊了第二個身份驗證因素。
使用第二個因素讓使用者登入
若要使用兩步驟簡訊驗證登入用戶:
使用第一個因素登入用戶,然後捕獲
auth/multi-factor-auth-required
錯誤。此錯誤包含解析器、有關註冊的第二個因素的提示以及證明使用者已成功通過第一個因素進行身份驗證的基礎會話。例如,如果使用者的第一個因素是電子郵件和密碼:
網路模組化API
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 命名空間 API
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()
後擷取錯誤。如果用戶註冊了多個次要因素,請詢問他們使用哪一個:
網路模組化API
// 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 if (resolver.hints[selectedIndex].factorId === TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. // ... } else { // Unsupported second factor. }
Web 命名空間 API
// 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 if (resolver.hints[selectedIndex].factorId === firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. // ... } else { // Unsupported second factor. }
如上一節所示初始化 reCAPTCHA 驗證器。如果已設定 RecaptchaVerifier 實例,請跳過此步驟:
網路模組化API
import { RecaptchaVerifier } from "firebase/auth"; recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
Web 命名空間 API
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
使用使用者的電話號碼和多因素會話初始化
PhoneInfoOptions
物件。這些值包含在傳遞給auth/multi-factor-auth-required
錯誤的resolver
物件中:網路模組化API
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };
Web 命名空間 API
var phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };
向用戶手機發送驗證簡訊:
網路模組化API
// 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 命名空間 API
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,然後重複上一步,以便使用者可以重試:
網路模組化API
recaptchaVerifier.clear();
Web 命名空間 API
recaptchaVerifier.clear();
發送簡訊代碼後,請用戶驗證該代碼:
網路模組化API
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
Web 命名空間 API
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
使用
PhoneAuthCredential
初始化MultiFactorAssertion
物件:網路模組化API
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web 命名空間 API
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
呼叫
resolver.resolveSignIn()
完成二次認證。然後,您可以存取原始登入結果,其中包括標準提供者特定的資料和身分驗證憑證:網路模組化API
// 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 命名空間 API
// 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. });
下面的程式碼顯示了登入多因素用戶的完整範例:
網路模組化API
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 if (resolver.hints[selectedIndex].factorId ===
TotpMultiFactorGenerator.FACTOR_ID) {
// Handle TOTP MFA.
// ...
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
}
});
Web 命名空間 API
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 if (resolver.hints[selectedIndex].factorId ===
firebase.auth.TotpMultiFactorGenerator.FACTOR_ID) {
// Handle TOTP MFA.
// ...
} else {
// Unsupported second factor.
}
} else if (error.code == 'auth/wrong-password') {
// Handle other errors such as wrong password.
} ...
});
恭喜!您使用多重身份驗證成功登入使用者。
下一步是什麼
- 使用 Admin SDK 以程式設計方式管理多因素使用者。