為您的 Android 應用程式添加多重身份驗證

如果您已升級至使用 Identity Platform 進行 Firebase 驗證,則可以將簡訊多重驗證新增至您的 Android 應用程式。

多重身份驗證可提高應用程式的安全性。雖然攻擊者經常破壞密碼和社交帳戶,但攔截簡訊卻更加困難。

在你開始之前

  1. 啟用至少一個支援多重身份驗證的提供者。每個提供者都支援 MFA,電話身份驗證、匿名身份驗證和 Apple Game Center除外

  2. 確保您的應用程式正在驗證使用者電子郵件。 MFA 需要電子郵件驗證。這可以防止惡意行為者使用不屬於他們的電子郵件註冊服務,然後透過添加第二個因素來鎖定真正的所有者。

  3. 在 Firebase 控制台中註冊您應用的 SHA-1 雜湊(您的變更將自動轉移到 Google Cloud Firebase)。

    1. 依照對客戶端進行身份驗證中的步驟取得應用程式的 SHA-1 雜湊值。

    2. 開啟Firebase 控制台

    3. 導航至項目設定

    4. 您的應用程式下,點擊 Android 圖示。

    5. 依照指導步驟新增 SHA-1 雜湊值。

啟用多重身份驗證

  1. 開啟 Firebase 控制台的驗證 > 登入方法頁面。

  2. 「進階」部分中,啟用簡訊多重身份驗證

    您還應該輸入用於測試應用程式的電話號碼。雖然可選,但強烈建議註冊測試電話號碼,以避免開發過程中受到限制。

  3. 如果您尚未授權套用的網域,請將其新增至 Firebase 控制台的「驗證」>「設定」頁面上的允許清單中。

選擇註冊模式

您可以選擇應用程式是否需要多重身份驗證,以及註冊用戶的方式和時間。一些常見的模式包括:

  • 將使用者的第二個因素註冊為註冊的一部分。如果您的應用程式需要對所有使用者進行多重身份驗證,請使用此方法。

  • 提供可跳過的選項以在註冊過程中註冊第二個因素。想要鼓勵但不要求多因素身份驗證的應用程式可能會更喜歡這種方法。

  • 提供從使用者帳戶或個人資料管理頁面(而非註冊畫面)新增第二個因素的功能。這最大限度地減少了註冊過程中的摩擦,同時仍為安全敏感的用戶提供多因素身份驗證。

  • 當使用者想要存取安全要求更高的功能時,需要逐步加入第二個因素。

註冊第二個因素

若要為用戶註冊新的次要因素:

  1. 重新驗證使用者身份。

  2. 要求使用者輸入他們的電話號碼。

  3. 為用戶獲取多因素會話:

    Kotlin+KTX

    user.multiFactor.session.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val multiFactorSession: MultiFactorSession? = task.result
        }
    }
    

    Java

    user.getMultiFactor().getSession()
      .addOnCompleteListener(
          new OnCompleteListener<MultiFactorSession>() {
          @Override
          public void onComplete(@NonNull Task<MultiFactorSession> task) {
            if (task.isSuccessful()) {
              MultiFactorSession multiFactorSession = task.getResult();
            }
          }
          });
    
  4. 建構一個OnVerificationStateChangedCallbacks物件來處理驗證過程中的不同事件:

    Kotlin+KTX

    val callbacks = object : OnVerificationStateChangedCallbacks() {
        override fun onVerificationCompleted(credential: PhoneAuthCredential) {
            // This callback will be invoked in two situations:
            // 1) Instant verification. In some cases, the phone number can be
            //    instantly verified without needing to send or enter a verification
            //    code. You can disable this feature by calling
            //    PhoneAuthOptions.builder#requireSmsValidation(true) when building
            //    the options to pass to PhoneAuthProvider#verifyPhoneNumber().
            // 2) Auto-retrieval. On some devices, Google Play services can
            //    automatically detect the incoming verification SMS and perform
            //    verification without user action.
            this@MainActivity.credential = credential
        }
    
        override fun onVerificationFailed(e: FirebaseException) {
            // This callback is invoked in response to invalid requests for
            // verification, like an incorrect phone number.
            if (e is FirebaseAuthInvalidCredentialsException) {
                // Invalid request
                // ...
            } else if (e is FirebaseTooManyRequestsException) {
                // The SMS quota for the project has been exceeded
                // ...
            }
            // Show a message and update the UI
            // ...
        }
    
        override fun onCodeSent(
            verificationId: String, forceResendingToken: ForceResendingToken
        ) {
            // The SMS verification code has been sent to the provided phone number.
            // We now need to ask the user to enter the code and then construct a
            // credential by combining the code with a verification ID.
            // Save the verification ID and resending token for later use.
            this@MainActivity.verificationId = verificationId
            this@MainActivity.forceResendingToken = forceResendingToken
            // ...
        }
    }
    

    Java

    OnVerificationStateChangedCallbacks callbacks =
    new OnVerificationStateChangedCallbacks() {
      @Override
      public void onVerificationCompleted(PhoneAuthCredential credential) {
        // This callback will be invoked in two situations:
        // 1) Instant verification. In some cases, the phone number can be
        //    instantly verified without needing to send or enter a verification
        //    code. You can disable this feature by calling
        //    PhoneAuthOptions.builder#requireSmsValidation(true) when building
        //    the options to pass to PhoneAuthProvider#verifyPhoneNumber().
        // 2) Auto-retrieval. On some devices, Google Play services can
        //    automatically detect the incoming verification SMS and perform
        //    verification without user action.
        this.credential = credential;
      }
      @Override
      public void onVerificationFailed(FirebaseException e) {
        // This callback is invoked in response to invalid requests for
        // verification, like an incorrect phone number.
        if (e instanceof FirebaseAuthInvalidCredentialsException) {
        // Invalid request
        // ...
        } else if (e instanceof FirebaseTooManyRequestsException) {
        // The SMS quota for the project has been exceeded
        // ...
        }
        // Show a message and update the UI
        // ...
      }
      @Override
      public void onCodeSent(
        String verificationId, PhoneAuthProvider.ForceResendingToken token) {
        // The SMS verification code has been sent to the provided phone number.
        // We now need to ask the user to enter the code and then construct a
        // credential by combining the code with a verification ID.
        // Save the verification ID and resending token for later use.
        this.verificationId = verificationId;
        this.forceResendingToken = token;
        // ...
      }
    };
    
  5. 使用使用者的電話號碼、多因素會話和回調初始化PhoneInfoOptions物件:

    Kotlin+KTX

    val phoneAuthOptions = PhoneAuthOptions.newBuilder()
        .setPhoneNumber(phoneNumber)
        .setTimeout(30L, TimeUnit.SECONDS)
        .setMultiFactorSession(MultiFactorSession)
        .setCallbacks(callbacks)
        .build()
    

    Java

    PhoneAuthOptions phoneAuthOptions =
      PhoneAuthOptions.newBuilder()
          .setPhoneNumber(phoneNumber)
          .setTimeout(30L, TimeUnit.SECONDS)
          .setMultiFactorSession(multiFactorSession)
          .setCallbacks(callbacks)
          .build();
    

    預設情況下,啟用即時驗證。若要停用它,請新增對requireSmsValidation(true)的呼叫。

  6. 向用戶手機發送驗證簡訊:

    Kotlin+KTX

    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
    

    Java

    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
    

    雖然不是必需的,但最佳做法是提前通知用戶他們將收到短信,並且適用標準費率。

  7. 發送簡訊代碼後,請用戶驗證該代碼:

    Kotlin+KTX

    // Ask user for the verification code.
    val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
    

    Java

    // Ask user for the verification code.
    PhoneAuthCredential credential
      = PhoneAuthProvider.getCredential(verificationId, verificationCode);
    
  8. 使用PhoneAuthCredential初始化MultiFactorAssertion物件:

    Kotlin+KTX

    val multiFactorAssertion
      = PhoneMultiFactorGenerator.getAssertion(credential)
    

    Java

    MultiFactorAssertion multiFactorAssertion
      = PhoneMultiFactorGenerator.getAssertion(credential);
    
  9. 完成報名。或者,您可以指定第二個因素的顯示名稱。這對於具有多個第二因素的使用者非常有用,因為電話號碼在身份驗證流程中被封鎖(例如,+1*****1234)。

    Kotlin+KTX

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    FirebaseAuth.getInstance()
        .currentUser
        ?.multiFactor
        ?.enroll(multiFactorAssertion, "My personal phone number")
        ?.addOnCompleteListener {
            // ...
        }
    

    Java

    // Complete enrollment. This will update the underlying tokens
    // and trigger ID token change listener.
    FirebaseAuth.getInstance()
      .getCurrentUser()
      .getMultiFactor()
      .enroll(multiFactorAssertion, "My personal phone number")
      .addOnCompleteListener(
          new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            // ...
          }
          });
    

下面的程式碼顯示了註冊第二個因素的完整範例:

Kotlin+KTX

val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
user.multiFactor.session
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            val multiFactorSession = task.result
            val phoneAuthOptions = PhoneAuthOptions.newBuilder()
                .setPhoneNumber(phoneNumber)
                .setTimeout(30L, TimeUnit.SECONDS)
                .setMultiFactorSession(multiFactorSession)
                .setCallbacks(callbacks)
                .build()
            // Send SMS verification code.
            PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
        }
    }

// Ask user for the verification code.
val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)

val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)

// Complete enrollment.
FirebaseAuth.getInstance()
    .currentUser
    ?.multiFactor
    ?.enroll(multiFactorAssertion, "My personal phone number")
    ?.addOnCompleteListener {
        // ...
    }

Java

MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
user.getMultiFactor().getSession()
  .addOnCompleteListener(
      new OnCompleteListener<MultiFactorSession>() {
      @Override
      public void onComplete(@NonNull Task<MultiFactorSession> task) {
        if (task.isSuccessful()) {
          MultiFactorSession multiFactorSession = task.getResult();
          PhoneAuthOptions phoneAuthOptions =
            PhoneAuthOptions.newBuilder()
                .setPhoneNumber(phoneNumber)
                .setTimeout(30L, TimeUnit.SECONDS)
                .setMultiFactorSession(multiFactorSession)
                .setCallbacks(callbacks)
                .build();
          // Send SMS verification code.
          PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
        }
      }
      });

// Ask user for the verification code.
PhoneAuthCredential credential =
  PhoneAuthProvider.getCredential(verificationId, verificationCode);

MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
// Complete enrollment.
FirebaseAuth.getInstance()
  .getCurrentUser()
  .getMultiFactor()
  .enroll(multiFactorAssertion, "My personal phone number")
  .addOnCompleteListener(
      new OnCompleteListener<Void>() {
      @Override
      public void onComplete(@NonNull Task<Void> task) {
        // ...
      }
      });

恭喜!您已成功為使用者註冊了第二個身份驗證因素。

使用第二個因素讓使用者登入

若要使用兩步驟簡訊驗證登入用戶:

  1. 使用第一個因素讓使用者登錄,然後擷取FirebaseAuthMultiFactorException異常。此錯誤包含一個解析器,您可以使用它來取得使用者註冊的第二個因素。它還包含一個底層會話,證明使用者透過第一個因素成功進行了身份驗證。

    例如,如果使用者的第一個因素是電子郵件和密碼:

    Kotlin+KTX

    FirebaseAuth.getInstance()
        .signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(
            OnCompleteListener { task ->
                if (task.isSuccessful) {
                    // User is not enrolled with a second factor and is successfully
                    // signed in.
                    // ...
                    return@OnCompleteListener
                }
                if (task.exception is FirebaseAuthMultiFactorException) {
                    // The user is a multi-factor user. Second factor challenge is
                    // required.
                    val multiFactorResolver =
                        (task.exception as FirebaseAuthMultiFactorException).resolver
                    // ...
                } else {
                    // Handle other errors, such as wrong password.
                }
            })
    

    Java

    FirebaseAuth.getInstance()
      .signInWithEmailAndPassword(email, password)
      .addOnCompleteListener(
          new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
              // User is not enrolled with a second factor and is successfully
              // signed in.
              // ...
              return;
            }
            if (task.getException() instanceof FirebaseAuthMultiFactorException) {
              // The user is a multi-factor user. Second factor challenge is
              // required.
              MultiFactorResolver multiFactorResolver = task.getException().getResolver();
              // ...
            } else {
              // Handle other errors such as wrong password.
            }
          }
          });
    

    如果使用者的第一個因素是聯合提供者(例如 OAuth),請在呼叫startActivityForSignInWithProvider()後擷取錯誤。

  2. 如果用戶註冊了多個次要因素,請詢問他們使用哪一個:

    Kotlin+KTX

    // Ask user which second factor to use.
    // You can get the list of enrolled second factors using
    //   multiFactorResolver.hints
    
    // Check the selected factor:
    if (multiFactorResolver.hints[selectedIndex].factorId
        === PhoneMultiFactorGenerator.FACTOR_ID
    ) {
        // User selected a phone second factor.
        val selectedHint =
            multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo
    } else if (multiFactorResolver.hints[selectedIndex].factorId
        === TotpMultiFactorGenerator.FACTOR_ID) {
        // User selected a TOTP second factor.
    } else {
        // Unsupported second factor.
    }
    

    Java

    // Ask user which second factor to use.
    // You can get the masked phone number using
    // resolver.getHints().get(selectedIndex).getPhoneNumber()
    // You can get the display name using
    // resolver.getHints().get(selectedIndex).getDisplayName()
    if ( resolver.getHints()
                   .get(selectedIndex)
                   .getFactorId()
                   .equals( PhoneMultiFactorGenerator.FACTOR_ID ) ) {
    // User selected a phone second factor.
    MultiFactorInfo selectedHint =
      multiFactorResolver.getHints().get(selectedIndex);
    } else if ( resolver
                  .getHints()
                  .get(selectedIndex)
                  .getFactorId()
                  .equals(TotpMultiFactorGenerator.FACTOR_ID ) ) {
      // User selected a TOTP second factor.
    } else {
    // Unsupported second factor.
    }
    
  3. 使用提示和多因素會話初始化PhoneAuthOptions物件。這些值包含在附加到FirebaseAuthMultiFactorException的解析器中。

    Kotlin+KTX

    val phoneAuthOptions = PhoneAuthOptions.newBuilder()
        .setMultiFactorHint(selectedHint)
        .setTimeout(30L, TimeUnit.SECONDS)
        .setMultiFactorSession(multiFactorResolver.session)
        .setCallbacks(callbacks) // Optionally disable instant verification.
        // .requireSmsValidation(true)
        .build()
    

    Java

    PhoneAuthOptions phoneAuthOptions =
      PhoneAuthOptions.newBuilder()
          .setMultiFactorHint(selectedHint)
          .setTimeout(30L, TimeUnit.SECONDS)
          .setMultiFactorSession(multiFactorResolver.getSession())
          .setCallbacks(callbacks)
          // Optionally disable instant verification.
          // .requireSmsValidation(true)
          .build();
    
  4. 向用戶手機發送驗證簡訊:

    Kotlin+KTX

    // Send SMS verification code
    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
    

    Java

    // Send SMS verification code
    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
    
  5. 發送簡訊代碼後,請用戶驗證該代碼:

    Kotlin+KTX

    // Ask user for the verification code. Then, pass it to getCredential:
    val credential =
        PhoneAuthProvider.getCredential(verificationId, verificationCode)
    

    Java

    // Ask user for the verification code. Then, pass it to getCredential:
    PhoneAuthCredential credential
        = PhoneAuthProvider.getCredential(verificationId, verificationCode);
    
  6. 使用PhoneAuthCredential初始化MultiFactorAssertion物件:

    Kotlin+KTX

    val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
    

    Java

    MultiFactorAssertion multiFactorAssertion
        = PhoneMultiFactorGenerator.getAssertion(credential);
    
  7. 呼叫resolver.resolveSignIn()完成二次認證。然後,您可以存取原始登入結果,其中包括標準提供者特定的資料和身分驗證憑證:

    Kotlin+KTX

    multiFactorResolver
        .resolveSignIn(multiFactorAssertion)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val authResult = task.result
                // AuthResult will also contain the user, additionalUserInfo,
                // and an 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, authResult.getAdditionalUserInfo() will contain data
                // related to Google provider that the user signed in with;
                // authResult.getCredential() will contain the Google OAuth
                //   credential;
                // authResult.getCredential().getAccessToken() will contain the
                //   Google OAuth access token;
                // authResult.getCredential().getIdToken() contains the Google
                //   OAuth ID token.
            }
        }
    

    Java

    multiFactorResolver
      .resolveSignIn(multiFactorAssertion)
      .addOnCompleteListener(
          new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
              AuthResult authResult = task.getResult();
              // AuthResult will also contain the user, additionalUserInfo,
              // and an 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, authResult.getAdditionalUserInfo() will contain data
              // related to Google provider that the user signed in with.
              // authResult.getCredential() will contain the Google OAuth
              // credential.
              // authResult.getCredential().getAccessToken() will contain the
              // Google OAuth access token.
              // authResult.getCredential().getIdToken() contains the Google
              // OAuth ID token.
            }
          }
          });
    

下面的程式碼顯示了登入多因素用戶的完整範例:

Kotlin+KTX

FirebaseAuth.getInstance()
    .signInWithEmailAndPassword(email, password)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // User is not enrolled with a second factor and is successfully
            // signed in.
            // ...
            return@addOnCompleteListener
        }
        if (task.exception is FirebaseAuthMultiFactorException) {
            val multiFactorResolver =
                (task.exception as FirebaseAuthMultiFactorException).resolver

            // Ask user which second factor to use. Then, get
            // the selected hint:
            val selectedHint =
                multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo

            // Send the SMS verification code.
            PhoneAuthProvider.verifyPhoneNumber(
                PhoneAuthOptions.newBuilder()
                    .setActivity(this)
                    .setMultiFactorSession(multiFactorResolver.session)
                    .setMultiFactorHint(selectedHint)
                    .setCallbacks(generateCallbacks())
                    .setTimeout(30L, TimeUnit.SECONDS)
                    .build()
            )

            // Ask user for the SMS verification code, then use it to get
            // a PhoneAuthCredential:
            val credential =
                PhoneAuthProvider.getCredential(verificationId, verificationCode)

            // Initialize a MultiFactorAssertion object with the
            // PhoneAuthCredential.
            val multiFactorAssertion: MultiFactorAssertion =
                PhoneMultiFactorGenerator.getAssertion(credential)

            // Complete sign-in.
            multiFactorResolver
                .resolveSignIn(multiFactorAssertion)
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        // User successfully signed in with the
                        // second factor phone number.
                    }
                    // ...
                }
        } else {
            // Handle other errors such as wrong password.
        }
    }

Java

FirebaseAuth.getInstance()
  .signInWithEmailAndPassword(email, password)
  .addOnCompleteListener(
      new OnCompleteListener<AuthResult>() {
      @Override
      public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
          // User is not enrolled with a second factor and is successfully
          // signed in.
          // ...
          return;
        }
        if (task.getException() instanceof FirebaseAuthMultiFactorException) {
          FirebaseAuthMultiFactorException e =
            (FirebaseAuthMultiFactorException) task.getException();

          MultiFactorResolver multiFactorResolver = e.getResolver();

          // Ask user which second factor to use.
          MultiFactorInfo selectedHint =
            multiFactorResolver.getHints().get(selectedIndex);

          // Send the SMS verification code.
          PhoneAuthProvider.verifyPhoneNumber(
            PhoneAuthOptions.newBuilder()
                .setActivity(this)
                .setMultiFactorSession(multiFactorResolver.getSession())
                .setMultiFactorHint(selectedHint)
                .setCallbacks(generateCallbacks())
                .setTimeout(30L, TimeUnit.SECONDS)
                .build());

          // Ask user for the SMS verification code.
          PhoneAuthCredential credential =
            PhoneAuthProvider.getCredential(verificationId, verificationCode);

          // Initialize a MultiFactorAssertion object with the
          // PhoneAuthCredential.
          MultiFactorAssertion multiFactorAssertion =
            PhoneMultiFactorGenerator.getAssertion(credential);

          // Complete sign-in.
          multiFactorResolver
            .resolveSignIn(multiFactorAssertion)
            .addOnCompleteListener(
                new OnCompleteListener<AuthResult>() {
                  @Override
                  public void onComplete(@NonNull Task<AuthResult> task) {
                  if (task.isSuccessful()) {
                    // User successfully signed in with the
                    // second factor phone number.
                  }
                  // ...
                  }
                });
        } else {
          // Handle other errors such as wrong password.
        }
      }
      });

恭喜!您使用多重身份驗證成功登入使用者。

下一步是什麼