Thêm tính năng xác thực đa yếu tố vào ứng dụng web

Nếu đã nâng cấp lên tính năng Xác thực Firebase bằng Nền tảng nhận dạng, bạn có thể thêm tính năng xác thực đa yếu tố qua SMS vào ứng dụng web của mình.

Tính năng xác thực đa yếu tố giúp tăng cường 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 mạng xã hội, nhưng việc chặn tin nhắn văn bản còn khó khăn hơn.

Trước khi bắt đầu

  1. Bật í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ợ tính năng MFA, ngoại trừ tính năng xác thực điện thoại, tính năng xác thực ẩn danh và Trung tâm trò chơi của Apple.

  2. Bật những khu vực bạn định dùng phương thức xác thực qua SMS. Firebase sử dụng chính sách chặn hoàn toàn khu vực liên quan đến SMS, giúp tạo dự án của bạn ở trạng thái an toàn hơn theo mặc định.

  3. Đảm bảo rằng ứng dụng của bạn đang xác minh email của người dùng. Tính năng MFA yêu cầu xác minh email. Thao tác này ngăn các đối tượng độc hại đăng ký một dịch vụ bằng email mà họ không sở hữu, sau đó khoá chủ sở hữu thực sự bằng cách thêm yếu tố thứ hai.

Sử dụng mạng đa người dùng

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 thành các bước sau (ngoài các bước hướng dẫn còn lại trong tài liệu này):

  1. Trong Bảng điều khiển của GCP, hãy chọn đối tượng thuê mà bạn muốn hợp tác.

  2. Trong mã của bạn, hãy đặt trường tenantId trên thực thể Auth thành mã nhận dạng của đối tượng thuê. Ví dụ:

    API mô-đun web

    import { getAuth } from "firebase/auth";
    
    const auth = getAuth(app);
    auth.tenantId = "myTenantId1";
    

    API không gian tên trên web

    firebase.auth().tenantId = 'myTenantId1';
    

Bật tính năng xác thực đa yếu tố

  1. Mở trang Xác thực > Phương thức đăng nhập trong bảng điều khiển của Firebase.

  2. 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 số điện thoại dùng để thử nghiệm ứ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 thử nghiệm để tránh tình trạng điều tiết trong quá trình phát triển.

  3. Nếu bạn chưa uỷ quyền miền của ứng dụng, hãy thêm miền này 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 của 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ố đối với 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ý. Các ứng dụng muốn khuyến khích nhưng không yêu cầu, có thể ưu tiên phương pháp này bằng tính năng xác thực đa yếu tố.

  • Cho phép 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ý. Việc này giúp giảm thiểu sự phiền hà trong quá trình đăng ký, trong khi 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ề bảo mật.

  • Yêu cầu thêm tăng dần 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

Bạn cần định cấu hình trình xác minh reCAPTCHA thì mới có thể gửi mã SMS. 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 phải thiết lập ứng dụng reCAPTCHA theo cách thủ công; đối tượng RecaptchaVerifier của SDK ứng dụng này sẽ tự động tạo và khởi chạy mọi khoá ứng dụng và khoá bí mật cần thiết.

Sử dụng reCAPTCHA vô hình

Đối tượng RecaptchaVerifier hỗ trợ reCAPTCHA vô hình, 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 vô hình, 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 đăng ký nhiều yếu tố:

API mô-đun web

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);

API không gian tên trên 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 tiện ích reCAPTCHA hiển thị, hãy tạo một phần tử HTML để chứa tiện ích này, 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:

API mô-đun web

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
);

API không gian tên trên 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ể kết xuất trước reCAPTCHA trước khi bắt đầu đăng ký hai yếu tố:

API mô-đun web

recaptchaVerifier.render()
    .then(function (widgetId) {
        window.recaptchaWidgetId = widgetId;
    });

API không gian tên trên web

recaptchaVerifier.render()
  .then(function(widgetId) {
    window.recaptchaWidgetId = widgetId;
  });

Sau khi render() phân giải, bạn sẽ nhận được mã tiện ích của reCAPTCHA. Bạn có thể dùng mã này để thực hiện lệnh gọi đến reCAPTCHA API:

var recaptchaResponse = grecaptcha.getResponse(window.recaptchaWidgetId);

ReCAPTCHAVerifier tóm tắt logic này bằng phương thức verify, vì vậy, 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:

  1. Xác thực lại người dùng.

  2. Yêu cầu người dùng nhập số điện thoại của họ.

  3. Khởi động trình xác minh reCAPTCHA như minh hoạ trong phần trước. Hãy bỏ qua bước này nếu bạn đã định cấu hình một bản sao RecaptchaVerifier:

    API mô-đun web

    import { RecaptchaVerifier } from "firebase/auth";
    
    const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
    

    API không gian tên trên web

    var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
    
  4. Nhận một phiên đa yếu tố cho người dùng:

    API mô-đun web

    import { multiFactor } from "firebase/auth";
    
    multiFactor(user).getSession().then(function (multiFactorSession) {
        // ...
    });
    

    API không gian tên trên web

    user.multiFactor.getSession().then(function(multiFactorSession) {
      // ...
    })
    
  5. Khởi động một đối tượng PhoneInfoOptions bằng số điện thoại của người dùng và phiên đa yếu tố:

    API mô-đun web

    // Specify the phone number and pass the MFA session.
    const phoneInfoOptions = {
      phoneNumber: phoneNumber,
      session: multiFactorSession
    };
    

    API không gian tên trên web

    // Specify the phone number and pass the MFA session.
    var phoneInfoOptions = {
      phoneNumber: phoneNumber,
      session: multiFactorSession
    };
    
  6. Gửi tin nhắn xác minh đến điện thoại của người dùng:

    API mô-đun 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.
        });
    

    API không gian tên trên 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 tốt nhất 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 cước tiêu chuẩn đó sẽ được áp dụng.

  7. 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 gửi lỗi, vì mã thông báo reCAPTCHA chỉ dùng được một lần.

    API mô-đun web

    recaptchaVerifier.clear();
    

    API không gian tên trên web

    recaptchaVerifier.clear();
    
  8. Sau khi gửi mã qua SMS, hãy yêu cầu người dùng xác minh mã:

    API mô-đun web

    // Ask user for the verification code. Then:
    const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
    

    API không gian tên trên web

    // Ask user for the verification code. Then:
    var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
    
  9. Khởi động đối tượng MultiFactorAssertion bằng PhoneAuthCredential:

    API mô-đun web

    import { PhoneMultiFactorGenerator } from "firebase/auth";
    
    const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
    

    API không gian tên trên web

    var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
    
  10. Hoàn tất quá 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 đối với những người dùng có nhiều yếu tố thứ hai, vì số điện thoại sẽ được che giấu trong quy trình xác thực (ví dụ: +1******1234).

    API mô-đun web

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    multiFactor(user).enroll(multiFactorAssertion, "My personal phone number");
    

    API không gian tên trên web

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    user.multiFactor.enroll(multiFactorAssertion, 'My personal phone number');
    

Mã bên dưới là ví dụ hoàn chỉnh về cách đăng ký yếu tố thứ hai:

API mô-đun web

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);
    });

API không gian tên trên 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 người dùng.

Đăng nhập người dùng bằng yếu tố thứ hai

Cách đăng nhập người dùng bằng tính năng xác minh hai yếu tố qua SMS:

  1. Đăng nhập cho người dùng bằng yếu tố đầu tiên, sau đó phát hiện lỗi auth/multi-factor-auth-required. Lỗi này chứa một trình phân giải lại, gợi ý về các yếu tố thứ hai đã đăng ký và một phiên cơ bản chứng minh 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:

    API mô-đun web

    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.
            }
    });
    

    API không gian tên trên 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 đượ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ặc signInWithRedirect().

  2. Nếu người dùng đã đăng ký nhiều yếu tố phụ, hãy hỏi họ chọn yếu tố nào:

    API mô-đun 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.
    }
    

    API không gian tên trên 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.
    }
    
  3. Khởi động trình xác minh reCAPTCHA như minh hoạ trong phần trước. Hãy bỏ qua bước này nếu bạn đã định cấu hình một bản sao RecaptchaVerifier:

    API mô-đun web

    import { RecaptchaVerifier } from "firebase/auth";
    
    recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth);
    

    API không gian tên trên web

    var recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container-id');
    
  4. Khởi động một đối tượng PhoneInfoOptions bằng số điện thoại của người dùng và phiên đa yếu tố. Các giá trị này nằm trong đối tượng resolver được truyền đến lỗi auth/multi-factor-auth-required:

    API mô-đun web

    const phoneInfoOptions = {
        multiFactorHint: resolver.hints[selectedIndex],
        session: resolver.session
    };
    

    API không gian tên trên web

    var phoneInfoOptions = {
      multiFactorHint: resolver.hints[selectedIndex],
      session: resolver.session
    };
    
  5. Gửi tin nhắn xác minh đến điện thoại của người dùng:

    API mô-đun 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.
        });
    

    API không gian tên trên 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.
      })
    
  6. 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:

    API mô-đun web

    recaptchaVerifier.clear();
    

    API không gian tên trên web

    recaptchaVerifier.clear();
    
  7. Sau khi gửi mã qua SMS, hãy yêu cầu người dùng xác minh mã:

    API mô-đun web

    const cred = PhoneAuthProvider.credential(verificationId, verificationCode);
    

    API không gian tên trên web

    // Ask user for the verification code. Then:
    var cred = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
    
  8. Khởi động đối tượng MultiFactorAssertion bằng PhoneAuthCredential:

    API mô-đun web

    const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(cred);
    

    API không gian tên trên web

    var multiFactorAssertion = firebase.auth.PhoneMultiFactorGenerator.assertion(cred);
    
  9. Hãy gọi 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:

    API mô-đun 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.
        });
    

    API không gian tên trên 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 vào tài khoản người dùng đa yếu tố:

API mô-đun web

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.
        }
    });

API không gian tên trên 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 vào 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