如果您已升級至 Firebase Authentication with Identity Platform,可以為網頁應用程式新增簡訊多重驗證。
多重驗證可提高應用程式的安全性。雖然攻擊者經常入侵遭外洩的密碼和社群帳戶,但攔截簡訊的難度較高。
事前準備
請至少啟用一個支援多重驗證的提供者。 除了電話驗證、匿名驗證和 Apple Game Center 以外,所有供應商都支援多重驗證。
啟用您打算使用簡訊驗證的區域。Authentication 採用完全封鎖的簡訊區域政策,根據預設,這項政策有助於在更安全的狀態下建立專案。
請確認應用程式會驗證使用者電子郵件地址。多重驗證需要電子郵件驗證。 這可防止惡意行為人使用不屬於自己的電子郵件註冊服務,然後新增第二個驗證因素,將真正的擁有者鎖在帳戶外。
使用多租戶架構
如要在多租戶環境中啟用多重驗證,請務必完成下列步驟 (以及本文中的其他操作說明):
在 Google Cloud 控制台中,選取要使用的租戶。
在程式碼中,將
Auth執行個體的tenantId欄位設為 租戶 ID。例如:Web
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";Web
firebase.auth().tenantId = 'myTenantId1';
啟用多重驗證
在 Firebase 控制台中,依序前往「Security」(安全性) >「Authentication」(驗證)。
在「Sign-in method」(登入方式) 分頁的「Advanced」(進階) 部分,啟用「SMS Multi-factor Authentication」(簡訊多重驗證)。
您也應輸入要用來測試應用程式的電話號碼。雖然這不是必要步驟,我們仍強烈建議您註冊測試電話號碼,以免在開發期間發生節流情形。
如果您尚未授權應用程式的網域,請按照下列步驟操作:
在 Firebase 控制台中,依序前往「Security」(安全性) >「Authentication」(驗證) >「Settings」(設定) 分頁標籤。
在「Authorized domains」(授權網域) 專區中,按一下「Add domain」(新增網域),然後新增網域。
選擇註冊模式
您可以選擇應用程式是否需要多重驗證,以及註冊使用者的時間和方式。常見的模式包括:
在註冊過程中,註冊使用者的第二驗證因素。如果應用程式要求所有使用者進行多重驗證,請使用這個方法。
在註冊期間提供可略過的雙重驗證註冊選項。如果應用程式想鼓勵 (而非強制) 使用者採用多重驗證,則可選擇這種做法。
請提供從使用者帳戶或設定檔管理頁面 (而非註冊畫面) 新增第二個驗證因素的功能。這樣可以盡量減少註冊程序中的阻礙,同時仍為重視安全性的使用者提供多重驗證。
當使用者想存取安全性要求較高的功能時,要求逐步新增第二重驗證資訊。
設定 reCAPTCHA 驗證器
您必須先設定 reCAPTCHA 驗證器,才能傳送簡訊驗證碼。Authentication 會使用 reCAPTCHA,確保電話號碼驗證要求來自應用程式允許的網域,防止濫用行為。
您不需要手動設定 reCAPTCHA 用戶端,用戶端 SDK 的 RecaptchaVerifier 物件會自動建立及初始化任何必要的用戶端金鑰和密鑰。
使用隱形 reCAPTCHA
RecaptchaVerifier 物件支援隱形 reCAPTCHA,通常不需要使用者互動就能驗證使用者。如要使用隱形 reCAPTCHA,請建立 RecaptchaVerifier,並將 size 參數設為 invisible,然後指定啟動多重驗證註冊程序的 UI 元素 ID:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(), "sign-in-button", {
"size": "invisible",
"callback": function(response) {
// reCAPTCHA solved, you can proceed with
// phoneAuthProvider.verifyPhoneNumber(...).
onSolvedRecaptcha();
}
});
Web
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
import { RecaptchaVerifier, getAuth } from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(
getAuth(),
"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.
// ...
}
}
);
Web
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:
Web
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
render() 解析後,您會取得 reCAPTCHA 的小工具 ID,可用於呼叫 reCAPTCHA API:
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier 會使用 verify 方法抽象化這個邏輯,因此您不需要直接處理 grecaptcha 變數。
註冊第二重驗證
如要為使用者註冊新的第二重驗證方法,請按照下列步驟操作:
重新驗證使用者。
請使用者輸入電話號碼。
按照上一節的說明,初始化 reCAPTCHA 驗證工具。如果已設定 RecaptchaVerifier 執行個體,請略過這個步驟:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth"; const recaptchaVerifier = new RecaptchaVerifier( getAuth(),'recaptcha-container-id', undefined);Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');為使用者取得多重驗證工作階段:
Web
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });Web
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })使用使用者的電話號碼和多重驗證工作階段,初始化
PhoneInfoOptions物件:Web
// Specify the phone number and pass the MFA session. const phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };Web
// Specify the phone number and pass the MFA session. var phoneInfoOptions = { phoneNumber: phoneNumber, session: multiFactorSession };傳送驗證訊息到使用者的手機:
Web
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
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,然後重複上一個步驟,讓使用者可以再試一次。請注意,reCAPTCHA 權杖只能使用一次,因此
verifyPhoneNumber()擲回錯誤時,會自動重設 reCAPTCHA。Web
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();簡訊驗證碼傳送後,請要求使用者驗證:
Web
// Ask user for the verification code. Then: const cred = PhoneAuthProvider.credential(verificationId, verificationCode);Web
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);使用
PhoneAuthCredential初始化MultiFactorAssertion物件:Web
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);完成註冊。您也可以視需要為第二個驗證碼指定顯示名稱。如果使用者有多個第二驗證因素,這項功能就非常實用,因為電話號碼會在驗證流程中遮蓋 (例如 +1******1234)。
Web
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");Web
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
以下程式碼顯示註冊第二個驗證方法的已完成樣本:
Web
import {
multiFactor, PhoneAuthProvider, PhoneMultiFactorGenerator,
RecaptchaVerifier, getAuth
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
'recaptcha-container-id', undefined);
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
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錯誤。這項錯誤包含解析器、已註冊第二驗證因素的提示,以及證明使用者已成功透過第一驗證因素完成驗證的基礎工作階段。舉例來說,如果使用者的第一驗證因素是電子郵件和密碼:
Web
import { getAuth, signInWithEmailAndPassword, 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
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()後擷取錯誤。如果使用者註冊了多個次要驗證因素,請詢問他們要使用哪一個:
Web
// 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
// 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 執行個體,請略過這個步驟:
Web
import { RecaptchaVerifier, getAuth } from "firebase/auth"; recaptchaVerifier = new RecaptchaVerifier(getAuth(), 'recaptcha-container-id', undefined);Web
var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');使用使用者的電話號碼和多重驗證工作階段,初始化
PhoneInfoOptions物件。這些值包含在傳遞至auth/multi-factor-auth-required錯誤的resolver物件中:Web
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };Web
var phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };傳送驗證訊息到使用者的手機:
Web
// 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
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
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();簡訊驗證碼傳送後,請要求使用者驗證:
Web
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);Web
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);使用
PhoneAuthCredential初始化MultiFactorAssertion物件:Web
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);請撥打
resolver.resolveSignIn()完成次要驗證。 接著,您可以存取原始登入結果,其中包含標準供應商專屬資料和驗證憑證:Web
// 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
// 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
import {
getAuth,
getMultiFactorResolver,
PhoneAuthProvider,
PhoneMultiFactorGenerator,
RecaptchaVerifier,
signInWithEmailAndPassword
} from "firebase/auth";
const recaptchaVerifier = new RecaptchaVerifier(getAuth(),
'recaptcha-container-id', undefined);
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
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 以程式輔助方式管理多重驗證使用者。