Nếu đã nâng cấp lên Xác thực Firebase với Nền tảng nhận dạng, bạn có thể thêm xác thực đa yếu tố SMS vào ứng dụng web của mình.
Xác thực đa yếu tố tăng tính bảo mật cho ứng dụng của bạn. Mặc dù những kẻ tấn công thường xâm phạm mật khẩu và tài khoản xã hội, nhưng việc chặn tin nhắn văn bản lại khó khăn hơn.
Trước khi bắt đầu
Cho phép ít nhất một nhà cung cấp hỗ trợ 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 điện thoại, xác thực ẩn danh và Trung tâm trò chơi Apple.
Đả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 các tác nhân độc hại đăng ký dịch vụ bằng email mà họ không sở hữu, sau đó khóa chủ sở hữu thực sự bằng cách thêm yếu tố thứ hai.
Sử dụng nhiều người thuê nhà
Nếu bạn đang bật xác thực đa yếu tố để sử dụng trong môi trường nhiều đối tượng thuê , hãy đảm bảo hoàn thành 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 GCP, hãy chọn đối tượng thuê mà bạn muốn làm việc cùng.
Trong mã của bạn, hãy đặt trường
tenantId
trên phiên bảnAuth
thành ID của đối tượng thuê của bạn. Ví dụ:Web version 9
import { getAuth } from "firebase/auth"; const auth = getAuth(app); auth.tenantId = "myTenantId1";
Web version 8
firebase.auth().tenantId = 'myTenantId1';
Kích hoạt 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 , bật Xác thực đa yếu tố SMS .
Bạn cũng nên nhập các số điện thoại mà bạn sẽ dùng để thử nghiệm ứng dụng của mình. Mặc dù là tùy chọn, nhưng bạn nên đăng ký số điện thoại thử nghiệm để tránh bị tắc nghẽn trong quá trình phát triển.
Nếu bạn chưa cấp phép 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.
Lựa chọn hình thức đă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 của bạn. Một số mẫu phổ biến bao gồm:
Đăng ký yếu tố thứ hai của người dùng như một phần của đăng ký. Sử dụng phương pháp 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 tùy chọn có thể bỏ qua để đăng ký yếu tố thứ hai trong quá trình đăng ký. Các ứ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ể thích phương pháp này hơn.
Cung cấp khả năng thêm yếu tố thứ hai từ trang quản lý hồ sơ hoặc tài khoản của người dùng, thay vì màn hình đăng ký. Điều này giảm thiểu trở ngại trong quá trình đăng ký, trong khi vẫn cung cấp xác thực đa yếu tố cho người dùng nhạy cảm về bảo mật.
Yêu cầu tăng dần yếu tố thứ hai khi người dùng muốn truy cập 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 lạm dụng 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 các miền được phép của ứng dụng của bạn.
Bạn không cần thiết lập ứng dụng khách reCAPTCHA theo cách thủ công; đối tượng RecaptchaVerifier
của SDK máy khách sẽ tự động tạo và khởi tạo mọi khóa và bí mật máy khách cần thiết.
Sử dụng reCAPTCHA vô hình
Đối tượng RecaptchaVerifier
hỗ trợ reCAPTCHA ẩn, thường có thể xác minh người dùng mà không yêu cầu bất kỳ tương tác nào. Để sử dụng reCAPTCHA ẩn, hãy tạo RecaptchaVerifier
với tham số size
được đặt thành invisible
được và chỉ định ID của phần tử giao diện người dùng bắt đầu đăng ký đa yếu tố:
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();
}
});
Sử dụng tiện ích reCAPTCHA
Để sử dụng 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 đối tượng RecaptchaVerifier
có ID của vùng chứa giao diện người dùng. Bạn cũng có thể tùy chọn đặt các cuộc gọi lại được gọi khi reCAPTCHA được giải quyết hoặc hết hạn:
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.
// ...
}
});
Hiển thị trước reCAPTCHA
Theo tùy chọn, bạn có thể hiển thị trước reCAPTCHA trước khi bắt đầu đăng ký hai yếu tố:
Web version 9
recaptchaVerifier.render()
.then(function (widgetId) {
window.recaptchaWidgetId = widgetId;
});
Web version 8
recaptchaVerifier.render()
.then(function(widgetId) {
window.recaptchaWidgetId = widgetId;
});
Sau khi render()
giải quyết xong, bạn sẽ nhận được ID tiện ích con của reCAPTCHA mà bạn có thể sử dụng để gọi tới API reCAPTCHA :
var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);
RecaptchaVerifier trừu tượng hóa logic này bằng phương thức xác minh , vì vậy bạn không cần xử lý trực tiếp biến grecaptcha
.
Ghi danh một yếu tố thứ hai
Để đă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 của họ.
Khởi tạo trình xác minh reCAPTCHA như minh họa trong phần trước. Bỏ qua bước này nếu phiên bản RecaptchaVerifier đã được định cấu hình:
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');
Nhận phiên đa yếu tố cho người dùng:
Web version 9
import { multiFactor } from "firebase/auth"; multiFactor(user).getSession().then(function (multiFactorSession) { // ... });
Web version 8
user.multiFactor.getSession().then(function(multiFactorSession) { // ... })
Khởi tạo một đối tượng
PhoneInfoOptions
với số điện thoại của người dùng và phiên đa yếu tố: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 };
Gửi tin nhắn xác minh đến điện thoại của người dùng:
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. })
Mặc dù không bắt buộc nhưng cách tốt nhất là 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. Lưu ý rằng
verifyPhoneNumber()
sẽ tự động đặt lại reCAPTCHA khi gặp lỗi vì mã thông báo reCAPTCHA chỉ được sử dụng một lần.Web version 9
recaptchaVerifier.clear();
Web version 8
recaptchaVerifier.clear();
Khi mã SMS được gửi, hãy yêu cầu người dùng xác minh mã:
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);
Khởi tạo một đối tượng
MultiFactorAssertion
vớiPhoneAuthCredential
:Web version 9
import { PhoneMultiFactorGenerator } from "firebase/auth"; const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web version 8
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
Hoàn thành việc ghi danh. Theo tùy chọ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 người dùng có nhiều yếu tố thứ hai, vì số điện thoại bị ẩn trong quy trình xác thực (ví dụ: +1******1234).
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');
Đ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 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);
});
Chúc mừng! Bạn đã đăng ký thành công yếu tố xác thực thứ hai cho người dùng.
Đăng nhập người dùng bằng yếu tố thứ hai
Để đăng nhập người dùng bằng xác minh SMS hai yếu tố:
Đăng nhập người dùng bằng yếu tố đầu tiên của họ, sau đó phát hiện lỗi
auth/multi-factor-auth-required
. Lỗi này chứa trình giải quyết, gợi ý về các yếu tố thứ hai đã đăng ký và phiên cơ bản chứng minh người dùng đã xác thực thành công với 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 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. } ... });
Nếu yếu tố đầu tiên của người dùng là nhà cung cấp được liên kết, chẳng hạn như OAuth, SAML hoặc OIDC, hãy phát hiện 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ọ nên sử dụng yếu tố nào:
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. }
Khởi tạo trình xác minh reCAPTCHA như minh họa trong phần trước. Bỏ qua bước này nếu phiên bản RecaptchaVerifier đã được định cấu hình:
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');
Khởi tạo một đối tượng
PhoneInfoOptions
với số điện thoại của người dùng và phiên đa yếu tố. Các giá trị này được chứa trong đối tượng trình phânresolver
được chuyển đến lỗiauth/multi-factor-auth-required
:Web version 9
const phoneInfoOptions = { multiFactorHint: resolver.hints[selectedIndex], session: resolver.session };
Web version 8
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 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. })
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 version 9
recaptchaVerifier.clear();
Web version 8
recaptchaVerifier.clear();
Khi mã SMS được gửi, hãy yêu cầu người dùng xác minh mã:
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);
Khởi tạo một đối tượng
MultiFactorAssertion
vớiPhoneAuthCredential
:Web version 9
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
Web version 8
var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
Gọi
resolver.resolveSignIn()
để hoàn thành xác thực phụ. Sau đó, bạn có thể truy cập kết quả đăng nhập ban đầu, bao gồm thông tin xác thực và dữ liệu dành riêng cho nhà cung cấp tiêu chuẩn: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. });
Mã bên dưới hiển thị một ví dụ hoàn chỉnh về cách đăng nhập người dùng đa yếu tố:
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.
} ...
});
Chúc mừng! Bạn đã đăng nhập thành công người dùng bằng xác thực đa yếu tố.
Cái gì tiếp theo
- Quản lý người dùng đa yếu tố theo chương trình với SDK quản trị.