Nếu đã nâng cấp lên Firebase Authentication with Identity Platform, bạn có thể thêm tính năng xác thực đa yếu tố bằng SMS vào ứng dụng web của mình.
Xác thực đa yếu tố giúp tăng cường tính bảo mật cho ứng dụng của bạn. Mặc dù kẻ tấn công thường xâm nhập mật khẩu và tài khoản mạng xã hội, nhưng việc chặn tin nhắn văn bản sẽ khó khăn hơn.
Trước khi bắt đầu
Bật ít nhất một nhà cung cấp hỗ trợ tính năng xác thực đa yếu tố. Mọi nhà cung cấp đều hỗ trợ MFA, ngoại trừ xác thực bằng điện thoại, xác thực ẩn danh và Apple Game Center.
Bật những khu vực mà bạn dự định sử dụng phương thức xác thực qua SMS. Firebase sử dụng chính sách khu vực SMS chặn hoàn toàn, giúp tạo các dự án của bạn ở trạng thái an toàn hơn theo mặc định.
Đảm bảo ứng dụng của bạn đang xác minh email của người dùng. MFA yêu cầu xác minh email. Điều này ngăn chặn các đối tượng xấu đăng ký một dịch vụ bằng email mà họ không sở hữu, sau đó chặn chủ sở hữu thực sự bằng cách thêm một yếu tố thứ hai.
Sử dụng mô hình nhiều đối tượng thuê
Nếu bạn đang bật tính năng xác thực đa yếu tố để sử dụng trong môi trường nhiều đối tượng thuê, hãy nhớ hoàn tất các bước sau (ngoài các hướng dẫn còn lại trong tài liệu này):
Trong bảng điều khiển Google Cloud, hãy chọn đối tượng thuê bao mà bạn muốn làm việc.
Trong mã của bạn, hãy đặt trường
tenantIdtrên thực thểAuththành mã nhận dạng của đối tượng thuê bao. Ví dụ:Web
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";Web
firebase.auth().tenantId = 'myTenantId1';
Bật tính năng xác thực đa yếu tố
Mở trang Xác thực > Phương thức đăng nhập của bảng điều khiển Firebase.
Trong phần Nâng cao, hãy bật chế độ Xác thực đa yếu tố qua SMS.
Bạn cũng nên nhập số điện thoại mà bạn sẽ dùng để kiểm thử ứng dụng. Mặc dù không bắt buộc, nhưng bạn nên đăng ký số điện thoại kiểm thử để tránh bị điều tiết trong quá trình phát triển.
Nếu bạn chưa uỷ quyền cho miền của ứng dụng, hãy thêm miền đó vào danh sách cho phép trên trang Xác thực > Cài đặt của bảng điều khiển Firebase.
Chọn một mẫu đăng ký
Bạn có thể chọn xem ứng dụng của mình có yêu cầu xác thực đa yếu tố hay không, cũng như cách thức và thời điểm đăng ký người dùng. Một số mẫu phổ biến bao gồm:
Đăng ký yếu tố thứ hai của người dùng trong quá trình đăng ký. Sử dụng phương thức này nếu ứng dụng của bạn yêu cầu xác thực đa yếu tố cho tất cả người dùng.
Cung cấp lựa chọn có thể bỏ qua để đăng ký yếu tố thứ hai trong quá trình đăng ký. Những ứng dụng muốn khuyến khích nhưng không yêu cầu xác thực đa yếu tố có thể ưu tiên phương pháp này.
Cung cấp khả năng thêm yếu tố thứ hai từ trang quản lý tài khoản hoặc hồ sơ của người dùng, thay vì màn hình đăng ký. Điều này giúp giảm thiểu phiền toái trong quá trình đăng ký, đồng thời vẫn cung cấp tính năng xác thực đa yếu tố cho những người dùng nhạy cảm với vấn đề bảo mật.
Yêu cầu tăng dần việc thêm yếu tố thứ hai khi người dùng muốn truy cập vào các tính năng có yêu cầu bảo mật cao hơn.
Thiết lập trình xác minh reCAPTCHA
Trước khi có thể gửi mã SMS, bạn cần định cấu hình trình xác minh reCAPTCHA. Firebase sử dụng reCAPTCHA để ngăn chặn hành vi sai trái bằng cách đảm bảo rằng các yêu cầu xác minh số điện thoại đến từ một trong những miền được phép của ứng dụng.
Bạn không cần thiết lập ứng dụng reCAPTCHA theo cách thủ công; đối tượng RecaptchaVerifier của SDK ứng dụng sẽ tự động tạo và khởi chạy mọi khoá và bí mật cần thiết của ứng dụng.
Sử dụng reCAPTCHA vô hình
Đối tượng RecaptchaVerifier hỗ trợ reCAPTCHA ẩn. Đối tượng này thường có thể xác minh người dùng mà không cần bất kỳ hoạt động tương tác nào. Để sử dụng reCAPTCHA ẩn, hãy tạo một RecaptchaVerifier có tham số size được đặt thành invisible và chỉ định mã nhận dạng của phần tử trên giao diện người dùng bắt đầu quy trình đăng ký nhiều yếu tố:
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();
}
});
Sử dụng tiện ích reCAPTCHA
Để sử dụng một tiện ích reCAPTCHA hiển thị, hãy tạo một phần tử HTML để chứa tiện ích đó, sau đó tạo một đối tượng RecaptchaVerifier bằng mã nhận dạng của vùng chứa giao diện người dùng. Bạn cũng có thể tuỳ ý đặt các lệnh gọi lại được gọi khi reCAPTCHA được giải quyết hoặc hết hạn:
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.
// ...
}
});
Kết xuất trước reCAPTCHA
Bạn có thể chọn kết xuất trước reCAPTCHA trước khi bắt đầu đăng ký xác thực hai yếu tố:
Web
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
Sau khi render() phân giải, bạn sẽ nhận được mã nhận dạng tiện ích reCAPTCHA. Bạn có thể dùng mã này để gọi API reCAPTCHA:
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier trừu tượng hoá logic này bằng phương thức verify, nên bạn không cần xử lý trực tiếp biến grecaptcha.
Đăng ký yếu tố thứ hai
Cách đăng ký một yếu tố phụ mới cho người dùng:
Xác thực lại người dùng.
Yêu cầu người dùng nhập số điện thoại.
Khởi chạy trình xác minh reCAPTCHA như minh hoạ trong phần trước. Bỏ qua bước này nếu bạn đã định cấu hình một thực thể 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');Lấy một phiên nhiều yếu tố cho người dùng:
Web
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });Web
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })Khởi động một đối tượng
PhoneInfoOptionsbằng số điện thoại của người dùng và phiên nhiều yếu tố: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 };Gửi tin nhắn xác minh đến điện thoại của người dùng:
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. })Mặc dù không bắt buộc, nhưng bạn nên thông báo trước cho người dùng rằng họ sẽ nhận được tin nhắn SMS và mức phí tiêu chuẩn sẽ được áp dụng.
Nếu yêu cầu không thành công, hãy đặt lại reCAPTCHA, sau đó lặp lại bước trước để người dùng có thể thử lại. Xin lưu ý rằng
verifyPhoneNumber()sẽ tự động đặt lại reCAPTCHA khi reCAPTCHA gặp lỗi, vì mã thông báo reCAPTCHA chỉ dùng được một lần.Web
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();Sau khi mã SMS được gửi, hãy yêu cầu người dùng xác minh mã:
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);Khởi động một đối tượng
MultiFactorAssertionbằngPhoneAuthCredential:Web
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);Hoàn tất quy trình đăng ký. Nếu muốn, bạn có thể chỉ định tên hiển thị cho yếu tố thứ hai. Điều này hữu ích cho những người dùng có nhiều yếu tố thứ hai, vì số điện thoại sẽ bị che trong quy trình xác thực (ví dụ: +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');
Đoạn mã dưới đây cho thấy một ví dụ hoàn chỉnh về việc đăng ký yếu tố thứ hai:
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);
});
Xin chúc mừng! Bạn đã đăng ký thành công yếu tố xác thực thứ hai cho một người dùng.
Đăng nhập người dùng bằng yếu tố thứ hai
Cách đăng nhập cho người dùng bằng tính năng xác minh qua SMS hai yếu tố:
Đăng nhập cho người dùng bằng yếu tố đầu tiên của họ, sau đó bắt lỗi
auth/multi-factor-auth-required. Lỗi này chứa một trình phân giải, gợi ý về các yếu tố thứ hai đã đăng ký và một phiên cơ bản chứng minh rằng người dùng đã xác thực thành công bằng yếu tố đầu tiên.Ví dụ: nếu yếu tố đầu tiên của người dùng là email và mật khẩu:
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. } ... });Nếu yếu tố đầu tiên của người dùng là một nhà cung cấp liên kết, chẳng hạn như OAuth, SAML hoặc OIDC, hãy bắt lỗi sau khi gọi
signInWithPopup()hoặcsignInWithRedirect().Nếu người dùng đã đăng ký nhiều yếu tố phụ, hãy hỏi họ muốn sử dụng yếu tố nào:
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. }Khởi chạy trình xác minh reCAPTCHA như minh hoạ trong phần trước. Bỏ qua bước này nếu bạn đã định cấu hình một thực thể 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');Khởi động một đối tượng
PhoneInfoOptionsbằng số điện thoại của người dùng và phiên nhiều yếu tố. Các giá trị này nằm trong đối tượngresolverđược truyền đến lỗiauth/multi-factor-auth-required:Web
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };Web
var phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };Gửi tin nhắn xác minh đến điện thoại của người dùng:
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. })Nếu yêu cầu không thành công, hãy đặt lại reCAPTCHA, sau đó lặp lại bước trước để người dùng có thể thử lại:
Web
recaptchaVerifier.clear();Web
recaptchaVerifier.clear();Sau khi mã SMS được gửi, hãy yêu cầu người dùng xác minh mã:
Web
const cred = PhoneAuthProvider.credential(verificationId, verificationCode);Web
// Ask user for the verification code. Then: var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);Khởi động một đối tượng
MultiFactorAssertionbằngPhoneAuthCredential:Web
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);Web
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);Gọi đến số
resolver.resolveSignIn()để hoàn tất quy trình xác thực phụ. Sau đó, bạn có thể truy cập vào kết quả đăng nhập ban đầu, bao gồm dữ liệu tiêu chuẩn dành riêng cho nhà cung cấp và thông tin xác thực: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. });
Đoạn mã dưới đây cho thấy một ví dụ hoàn chỉnh về việc đăng nhập cho người dùng có nhiều yếu tố:
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.
} ...
});
Xin chúc mừng! Bạn đã đăng nhập thành công cho một người dùng bằng tính năng xác thực đa yếu tố.
Bước tiếp theo
- Quản lý người dùng xác thực đa yếu tố theo phương thức lập trình bằng Admin SDK.