Ajouter l'authentification multifacteur à votre application Android

Ce document explique comment ajouter l'authentification multifacteur par SMS à votre application Android.

L'authentification multifacteur renforce la sécurité de votre application. Bien que les pirates informatiques compromettent les mots de passe et les comptes de réseaux sociaux, l'interception des SMS est plus difficile.

Avant de commencer

  1. Activez au moins un fournisseur compatible avec l'authentification multifacteur. Tous les fournisseurs sont compatibles avec la MFA, sauf l'authentification par téléphone, l'authentification anonyme et l'Apple Game Center.

  2. Assurez-vous que votre application valide les adresses e-mail des utilisateurs. L'authentification multifacteur nécessite une validation de l'adresse e-mail. Cela empêche les utilisateurs malveillants de s'enregistrer à un service avec une adresse e-mail dont ils ne sont pas propriétaire, puis de bloquer le propriétaire réel en ajoutant un second facteur.

  3. Enregistrez le hachage SHA-1 de votre application dans la console Firebase (vos modifications sont automatiquement appliquées à Google Cloud Identity Platform).

    1. Suivez les étapes de la page Authentifier votre client pour obtenir le hachage SHA-1 de votre application.

    2. Ouvrez la console Firebase.

    3. Accédez aux Paramètres du projet.

    4. Sous Vos applications, cliquez sur l'icône Android.

    5. Suivez la procédure guidé pour ajouter votre hachage SHA-1.

Activer l'authentification multifacteur

  1. Accédez à la page Identity Platform MFA dans la console Google Cloud.
    Accéder à la MFA

  2. Dans Authentification multifacteur, cliquez sur Activer.

  3. Saisissez les numéros de téléphone avec lesquels vous souhaitez tester votre application. Bien que cette étape soit facultative, il est fortement recommandé d'enregistrer des numéros de téléphone de test pour éviter toute limitation lors du développement.

  4. Si vous n'avez pas encore autorisé le domaine de votre application, ajoutez-le à la liste d'autorisation en cliquant sur Ajouter un domaine.

  5. Cliquez sur Enregistrer.

Choisir un modèle d'inscription

Vous pouvez décider si votre application nécessite une authentification multifacteur, et comment et quand inscrire vos utilisateurs. Voici quelques modèles courants :

  • Inscrivez le deuxième facteur de l'utilisateur dans le cadre de l'inscription. Utilisez cette méthode si votre application nécessite une authentification multifacteur pour tous les utilisateurs.

  • Proposez une option désactivable pour inscrire un second facteur lors de l'enregistrement. Les applications qui souhaitent encourager l'authentification multifacteur, mais ne l'exigent pas, peuvent préférer cette approche.

  • Offrez la possibilité d'ajouter un second facteur à partir de la page de gestion de compte ou de profil de l'utilisateur, au lieu de l'écran d'inscription. Cela minimise les frictions lors du processus d'enregistrement tout en rendant encore l'authentification multifacteur disponible pour les utilisateurs sensibles à la sécurité.

  • Exigez l'ajout incrémentiel d'un second facteur lorsque l'utilisateur souhaite accéder aux fonctionnalités présentant des exigences de sécurité accrues.

Inscrire un second facteur

Pour inscrire un nouveau facteur secondaire pour un utilisateur, procédez comme suit :

  1. Réauthentifiez l'utilisateur.

  2. Demandez à l'utilisateur de saisir son numéro de téléphone.

  3. Obtenez une session multifacteur pour l'utilisateur :

    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. Créez un objet OnVerificationStateChangedCallbacks pour gérer différents événements dans le processus de validation :

    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. Initialisez un objet PhoneInfoOptions avec le numéro de téléphone de l'utilisateur, la session multifacteur et vos rappels :

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

    La validation instantanée est activée par défaut. Pour la désactiver, ajoutez un appel à requireSmsValidation(true).

  6. Envoyez un message de validation sur le téléphone de l'utilisateur :

    Kotlin+KTX

    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
    

    Java

    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
    

    Bien que cela ne soit pas obligatoire, il est recommandé d'informer préalablement les utilisateurs qu'ils recevront un SMS, et que les tarifs standards s'appliquent.

  7. Une fois le code SMS envoyé, demandez à l'utilisateur de le vérifier :

    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. Initialisez un objet MultiFactorAssertion à l'aide du PhoneAuthCredential :

    Kotlin+KTX

    val multiFactorAssertion
      = PhoneMultiFactorGenerator.getAssertion(credential)
    

    Java

    MultiFactorAssertion multiFactorAssertion
      = PhoneMultiFactorGenerator.getAssertion(credential);
    
  9. Terminez l'inscription. Vous pouvez éventuellement spécifier un nom à afficher pour le deuxième facteur. Cela s'avère utile pour les utilisateurs qui ont plusieurs facteurs, car le numéro de téléphone est masqué pendant le processus d'authentification (par exemple, +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) {
            // ...
          }
          });
    

Le code ci-dessous montre un exemple complet d'inscription d'un second facteur :

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

Félicitations ! Vous avez enregistré un second facteur d'authentification pour un utilisateur.

Connecter des utilisateurs avec un second facteur

Pour connecter un utilisateur via la validation SMS à deux facteurs, procédez comme suit :

  1. Connectez l'utilisateur avec son premier facteur, puis détectez l'exception FirebaseAuthMultiFactorException. Cette erreur contient un résolveur, que vous pouvez utiliser pour obtenir les seconds facteurs inscrits de l'utilisateur. Elle contient également une session sous-jacente attestant que l'utilisateur s'est authentifié avec succès avec son premier facteur.

    Par exemple, si le premier facteur de l'utilisateur est une adresse e-mail et un mot de passe :

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

    Si le premier facteur de l'utilisateur est un fournisseur fédéré, tel que OAuth, détectez l'erreur après avoir appelé startActivityForSignInWithProvider().

  2. Si l'utilisateur possède plusieurs facteurs secondaires inscrits, demandez-lui lequel utiliser :

    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. Initialisez un objet PhoneAuthOptions avec l'optimisation et la session multifacteur. Ces valeurs sont contenues dans le résolveur associé à 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. Envoyez un message de validation sur le téléphone de l'utilisateur :

    Kotlin+KTX

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

    Java

    // Send SMS verification code
    PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
    
  5. Une fois le code SMS envoyé, demandez à l'utilisateur de le vérifier :

    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. Initialisez un objet MultiFactorAssertion à l'aide du PhoneAuthCredential :

    Kotlin+KTX

    val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
    

    Java

    MultiFactorAssertion multiFactorAssertion
        = PhoneMultiFactorGenerator.getAssertion(credential);
    
  7. Appelez resolver.resolveSignIn() pour terminer l'authentification secondaire. Vous pouvez ensuite accéder au résultat de connexion d'origine, qui inclut les données spécifiques au fournisseur et les identifiants d'authentification :

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

Le code ci-dessous illustre un exemple complet de connexion d'un utilisateur multifacteur :

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

Félicitations ! Vous avez connecté un utilisateur à l'aide de l'authentification multifacteur.

Étapes suivantes