如果您已升級至 Firebase Authentication with Identity Platform,可以為網頁應用程式新增簡訊多重驗證。
多重驗證可以為應用程式提供更完善的安全防護機制。攻擊者通常會竊取密碼及盜用社群媒體帳戶,但簡訊攔截則牽涉較為複雜的作業。
事前準備
啟用至少一個支援多重驗證的供應商。 所有供應商都支援多重驗證,但電話驗證、匿名驗證和 Apple Game Center 除外。
啟用您打算使用 SMS 驗證的區域。 Firebase 使用完全封鎖的簡訊區域政策,預設可協助您以更安全的狀態建立專案。
確認應用程式會驗證使用者電子郵件地址。多重驗證需要電子郵件驗證。 這樣一來,惡意人士就無法使用不屬於自己的電子郵件註冊服務,然後新增第二個驗證因素,將真正的擁有者鎖在門外。
使用多用戶群架構
如果您要啟用多重驗證,以便在多租戶環境中使用,請務必完成下列步驟 (以及本文中的其餘操作說明):
在 Google Cloud 控制台中,選取要使用的租戶。
在程式碼中,將
Auth執行個體上的tenantId欄位設為租戶的 ID。例如:Web
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";Web
firebase.auth().tenantId = 'myTenantId1';
啟用多重驗證
在「進階」部分,啟用「簡訊多重驗證」。
您也應輸入要用來測試應用程式的電話號碼。 雖然這不是必要步驟,我們仍強烈建議您註冊測試電話號碼,以免在開發期間發生節流情形。
如果尚未授權應用程式的網域,請前往 Firebase 控制台的「Authentication」>「Settings」頁面,將網域加入許可清單。
選擇註冊模式
您可以選擇應用程式是否需要多重驗證,以及如何和何時註冊使用者。常見的模式包括:
在註冊程序中,為使用者註冊第二個驗證因素。如果您的應用程式要求所有使用者啟用多重驗證,請使用這個方法。
在註冊期間提供可略過的選項,讓使用者註冊第二重驗證。如果應用程式希望使用者啟用多重驗證,但並非強制要求,建議採用這種做法。
讓使用者在帳戶或個人資料管理頁面新增第二個驗證要素,而非在註冊畫面新增。這樣可減少註冊程序中的阻礙,同時仍為注重安全性的使用者提供多重驗證。
當使用者想存取安全性要求較高的功能時,逐步要求新增第二個驗證要素。
設定 reCAPTCHA 驗證器
您必須先設定 reCAPTCHA 驗證器,才能傳送簡訊驗證碼。 Firebase 會使用 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,然後重複上一個步驟,讓使用者再次嘗試。請注意,
verifyPhoneNumber()擲回錯誤時會自動重設 reCAPTCHA,因為 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,以程式輔助的方式管理多重驗證使用者。