Enable SMS toll fraud protection for SMS-based authentication

This document explains how you can use reCAPTCHA to protect your Identity Platform SMS-based flows, such as phone and multi-factor authentication, against SMS toll fraud (also known as SMS pumping attacks).

Overview

If your app relies on an SMS-based flow for authentication, you can enable the reCAPTCHA SMS toll fraud protection feature as part of the Identity Platform integration with reCAPTCHA. When enabled, Identity Platform invokes the SMS toll fraud protection feature when a user requests a verification SMS from your app or site using the following phoneProvider operations:

Operation Method
Phone number sign up or sign in sendVerificationCode
MFA phone number enrollment mfaSmsEnrollment
MFA phone number sign in mfaSmsSignIn

reCAPTCHA then provides Identity Platform with a risk score that indicates the likelihood that the user's phone number will commit SMS toll fraud. Identity Platform compares this score to the threshold you set in your SMS toll fraud protection configuration and then handles the request based on the action you've set in your configuration.

For more information on the reCAPTCHA SMS toll fraud protection feature, see Detect and prevent SMS fraud.

Before you begin

Before you enable SMS toll fraud protection for Identity Platform, complete the following tasks:

  • Configure the following for your app or site as applicable:

  • If you haven't already done so, create a service account for each project that will use reCAPTCHA. For instructions, see Create a service account.

reCAPTCHA phone authentication enforcement modes

reCAPTCHA SMS toll fraud protection requires that you've set up reCAPTCHA phone authentication enforcement, which has two modes: audit and enforce.

Audit mode

When you set phone authentication enforcement to audit mode, Identity Platform uses reCAPTCHA SMS toll fraud protection for app verification. If the user request passes the toll fraud assessment, Identity Platform sends an SMS message containing a verification code to the user's phone. If a request fails the toll fraud assessment and you are using the client SDK, fallback verification methods are triggered to complete the phone authentication flow. The fallback methods accepted depend on your app's platform.

The client SDK triggers the fallback verification methods in the following scenarios:

  • The reCAPTCHA token is missing.
  • The reCAPTCHA token is invalid or expired.
  • The reCAPTCHA token doesn't pass the score threshold.
  • reCAPTCHA is not configured correctly.

Ensure that the fallback verification methods for your app's platform are set up and ready to be triggered by the client SDK if necessary.

Web

If the initial toll fraud assessment fails, audit mode relies on reCAPTCHA v2 for verification. Therefore, you must set up the reCAPTCHA verifier (RecaptchaVerifier) and pass it to the following phone authentication operations:

  • verifyPhoneNumber
  • signInWithPhoneNumber
  • linkWithPhoneNumber
  • reauthenticateWithPhoneNumber
Without the reCAPTCHA verifier, Identity Platform can't initiate reCAPTCHA v2 and will return auth/argument-error. For more information on setting up the reCAPTCHA verifier, see Set up the reCAPTCHA verifier in the Firebase documentation.

Android

If the initial toll fraud assessment fails, audit mode verifies your app against the Play Integrity API. If this verification fails, reCAPTCHA v2 is triggered. reCAPTCHA v2 might be triggered in the following scenarios:

  • If the end-user's device does not have Google Play services installed.
  • If the app is not distributed through Google Play Store (on Authentication SDK v21.2.0 and later).
  • If the obtained SafetyNet token was not valid (on Authentication SDK versions prior to v21.2.0).
For more information on setting up Android app verification, see Enable app verification in the Firebase documentation.

Enforce mode

When you set phone authentication enforcement to enforce mode, Identity Platform uses reCAPTCHA SMS toll fraud protection for app verification. If the user request passes the toll fraud assessment, Identity Platform sends an SMS message containing a verification code to the user's phone. If the request fails the toll fraud assessment, Identity Platform blocks the request and doesn't send an SMS message containing a verification code.

There is no fallback verification required in enforce mode, you don't have to set up any additional verification methods for your app. However, we recommend setting up reCAPTCHA verifier for web apps to ensure that reCAPTCHA v2 is enabled if you decide to change your app's reCAPTCHA mode to AUDIT or OFF.

Enable reCAPTCHA SMS toll fraud protection

To enable SMS toll fraud protection, do the following:

  1. If you haven't already done so, enable the reCAPTCHA Enterprise API on your project.

  2. Enable SMS toll fraud protection with reCAPTCHA. For instructions, see the Before you begin section of the Detect and prevent SMS fraud page in the reCAPTCHA documentation.

  3. To enable SMS toll fraud protection for a project, use the Admin SDK to call updateConfig as follows:

      // Update the reCAPTCHA config to enable toll fraud protection
      const updateProjectConfigRequest = {
        recaptchaConfig: {
          phoneEnforcementState: 'ENFORCE_MODE',
          useSmsTollFraudProtection: 'true',
          tollFraudManagedRules: [{ startScore: START_SCORE,
            action: 'BLOCK' }],
        }
      }
      let projectConfig = await getAuth().projectConfigManager().updateProject(updateProjectConfigRequest);
    

    Replace the following:

    • ENFORCE_MODE: the mode you want to set for reCAPTCHA phone authentication enforcement. Valid values are OFF, AUDIT, and ENFORCE. To enable SMS toll fraud protection, this parameter must be set to AUDIT or ENFORCE and useSmsTollFraudProtection must be set to true.

      When enabling SMS toll fraud protection for the first time, we recommend setting the enforcement state to AUDIT and ensuring your authentication flows are protected before setting this to ENFORCE. For more information on how the modes work, see reCAPTCHA phone authentication enforcement modes.

    • START_SCORE: the highest toll fraud assessment score a request can have before it fails. You can set this score to be between 0.0 and 1.0. Any score above the threshold you set will be considered SMS toll fraud. For example, if you set a threshold of 0.3, reCAPTCHA will fail any request with a 0.4 or higher. Therefore, the lower you set the score, the stricter the rules will be.

  4. If you are using Identity Platform on the web or Android, register your app from the Firebase console:

    reCAPTCHA key provisioning can take several minutes to complete.

  5. If you've set enforcement to audit mode, we recommend that you monitor the reCAPTCHA metrics for SMS toll fraud protection to ensure that your flows are being protected.

Configure the client SDK

Configure the client SDK according to your app's platform.

Web

  1. Update to the latest version of the web SDK.

    • reCAPTCHA support for email and password authentication in web apps is available on JavaScript SDK versions 9.20.0 and later.
    • reCAPTCHA support for phone authentication in web apps is available on JavaScript SDK versions 11 and later.

    After you've integrated the web SDK with your app, the SDK automatically fetches your reCAPTCHA configuration and enables protection for the providers you've configured.

  2. To reduce the number of network calls made by the SDK and improve reCAPTCHA signal collection, we recommend configuring it explicitly as follows:

    import { initializeRecaptchaConfig } from '@firebase/auth';
    
    // Initialize Firebase Authentication
    const auth = getAuth();
    initializeRecaptchaConfig(auth)
      .then(() => {
        console.log("Recaptcha Enterprise Config Initialization successful.")
      })
      .catch((error) => {
        console.error("Recaptcha Enterprise Config Initialization failed with " + error)
      });
    

Android

  1. Update to the latest version of the Android SDK. reCAPTCHA support for email and password authentication and phone authentication in Android apps is available on Android SDK version 23.1.0 and later.

    In addition, reCAPTCHA support requires API level 23 (Marshmallow) or higher and Android 6 or higher.

    After you've integrated the Android SDK with your app, the SDK automatically fetches your reCAPTCHA configuration and enables protection for the providers you've configured.

  2. Add the following build rule to the dependencies section of your app-level build.gradle file:

    implementation 'com.google.android.recaptcha:recaptcha:18.5.1'
    

    Make sure to use reCAPTCHA SDK version 18.5.1 or later.

  3. To reduce the number of network calls made by the SDK and to make reCAPTCHA signal collection more effective, we recommend configuring it explicitly as follows:

    • Kotlin:
    // Initialize Firebase Authentication
    auth = Firebase.auth
    
    auth.initializeRecaptchaConfig().addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Recaptcha Enterprise Initialization successful.")
        } else {
            Log.w(TAG, "Recaptcha Enterprise Initialization failed.")
        }
    }
    
    • Java:
    // Initialize Firebase Authentication
    auth = FirebaseAuth.getInstance();
    auth.initializeRecaptchaConfig().addOnCompleteListener(
      this, new OnCompleteListener<void>() {
      @Override
      public void onComplete(@NonNull Task<void> task) {
        if (task.isSuccessful()) {
          Log.d(TAG, "Recaptcha Enterprise Initialization successful.");
        } else {
          Log.w(TAG, "Recaptcha Enterprise Initialization failed.");
        }
      }
    });
    

iOS

Phone authentication flows on iOS are not supported by the Identity Platform integration with the reCAPTCHA Enterprise API.

  1. Update to iOS SDK version 10.14.0 or later. After you've integrated the iOS SDK with your app, the SDK automatically fetches your reCAPTCHA configuration and enables protection for the providers you've configured.

  2. To integrate reCAPTCHA iOS SDK to your app, see Prepare your environment.

  3. Ensure that -ObjC is listed in your linker flags. Navigate to Target > Build Settings > All > Linking and verify that Other Linker Flags shows -ObjC.

  4. To reduce the number of network calls made by the SDK and to make reCAPTCHA signal collection more effective, we recommend that you configure it explicitly, as follows:

    • Swift:
    // Initialize Firebase Authentication
    try await Auth.auth().initializeRecaptchaConfig()
    
    • Objective-C:
    // Initialize Firebase Authentication
    [[FIRAuth auth] initializeRecaptchaConfigWithCompletion:^(NSError * _Nullable error) {
      // Firebase Authentication initialization finished
    }];
    

Monitor reCAPTCHA metrics for SMS toll fraud protection

Before you set the reCAPTCHA enforcement to enforce mode, we recommend you use audit mode and monitor the reCAPTCHA metrics your project emits to ensure that your SMS-based authentication flows are protected. For example, these metrics can help you determine if you've set up the Identity Platform integration with the reCAPTCHA Enterprise API correctly. They can also help you fine-tune your score threshold for your user traffic.

Ensure that the SMS toll fraud protection feature is working by examining the following metrics your project emits to Cloud Monitoring:

For more information, see Monitor reCAPTCHA metrics.

Enforce SMS toll fraud protection

After you verify that your app is receiving acceptable user traffic, you can enable reCAPTCHA enforcement to protect your users. Ensure you don't disrupt existing users, including users who may be using an older version of your app.

To enable reCAPTCHA enforcement for SMS-based authentication flows on a project or tenant, use the Admin SDK to run the following command:

  const enforceRequest = {
    recaptchaConfig: {
      phoneEnforcementState:  'ENFORCE',
      useSmsTollFraudProtection: 'true'
    }
  };

Disable SMS toll fraud protection

To disable SMS toll fraud protection, use the Admin SDK to run the following command:

  const disableRequest = {
    recaptchaConfig: {
      phoneEnforcementState:  'OFF',
      useSmsTollFraudProtection: 'false'
    }
  };

To disable SMS toll fraud protection while you are using bot protection, see Disable SMS toll fraud protection while using bot protection.

Use SMS toll fraud protection with bot protection

It is possible to use SMS toll fraud protection simultaneously with bot protection. For configurations that use both protection features, consider the following:

  • When you've set the phone authentication enforcement state to audit, Identity Platform passes a request when it satisfies at least one of the assessments. We encourage you to monitor the reCAPTCHA metrics to ensure both SMS toll fraud protection and bot protection are configured with reasonable score settings.
  • When you've set the phone authentication enforcement state to enforce, Identity Platform only passes a request when it satisfies both assessments and the request fail closes without falling back to another verification method.

To enable both features, use the Admin SDK to run the following command:

  const enableBothRequest = {
    recaptchaConfig: {
      phoneEnforcementState:  'ENFORCE_MODE',
      useSmsTollFraudProtection: true,
      useSmsBotScore: true
    }
  };

Replace ENFORCE_MODE with the mode you want to set for reCAPTCHA phone authentication enforcement. Valid values are OFF, AUDIT, and ENFORCE. To enable SMS toll fraud protection, this parameter must be set to AUDIT or ENFORCE. When enabling SMS toll fraud protection for the first time, we recommend setting this parameter to AUDIT and ensuring your authentication flows are protected before setting this to ENFORCE. For more information on how the modes work, see reCAPTCHA phone authentication enforcement modes.

Disable SMS toll fraud protection while using bot protection

If you are using both SMS toll fraud protection and bot protection simultaneously, and you want to disable SMS toll fraud protection without disabling bot protection, use the Admin SDK to run the following command:

  const disableRequest = {
    recaptchaConfig: {
      phoneEnforcementState:  'ENFORCE_MODE',
      useSmsTollFraudProtection: 'false',
      useSmsBotScore: 'true'
    }
  };

Replace ENFORCE_MODE with the mode you've previously set for reCAPTCHA phone authentication enforcement. This value should be either AUDIT or ENFORCE. For more information on how the modes work, see reCAPTCHA phone authentication enforcement modes.

What's next