Integrate Identity Platform with the reCAPTCHA Enterprise API

This document shows you how to use the Identity Platform integration with the reCAPTCHA Enterprise API to enhance security for your users. This feature makes your app more resilient against spam, abuse, and other fraudulent activity.

The integration creates a reCAPTCHA Enterprise assessment on your behalf to validate user requests. For pricing information, see reCAPTCHA pricing.

Overview

When you set up the Identity Platform integration with the reCAPTCHA Enterprise API, you enable reCAPTCHA's default protection feature—reCAPTCHA bot protection. With bot protection, Identity Platform provisions score-based reCAPTCHA keys in your project on your behalf. When a user accesses your app or site using any of the following operations, the client SDK loads reCAPTCHA when the corresponding provider is enabled.

Provider Operation Method
passwordProvider Email and password sign-in signInWithPassword
Email and password sign-up signUpPassword
Email link sign-in getOobCode
Password reset getOobCode
phoneProvider 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 scores that assess the risk of the request based on your configuration and risk tolerance.

For more information, see Overview of reCAPTCHA.

Before you begin

Based on the type of authentication flow you want to protect with reCAPTCHA, ensure that you've set up the following:

  • For email-password authentication flows, ensure that you have configured email sign-in for users.
  • For SMS-based authentication flows, ensure that you have onboarded to at least one of the following:

Create a service account

The Identity Platform integration with the reCAPTCHA Enterprise API requires a Identity Platform service account for each project that will use reCAPTCHA. This allows Identity Platform to manage reCAPTCHA keys on your behalf. If you've already created a service account, grant it access to reCAPTCHA.

If you haven't already created a service account or you have additional projects that you want to protect with reCAPTCHA, do the following:

  1. Use the Google Cloud CLI to create a service account:

    gcloud beta services identity create \
        --service=identitytoolkit.googleapis.com \
        --project=PROJECT_ID
    

    Replace PROJECT_ID with the project's ID.

  2. Grant the service account access to reCAPTCHA:

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-identitytoolkit.iam.gserviceaccount.com \
        --role=roles/identitytoolkit.serviceAgent
    

    Replace the following:

    • PROJECT_ID: the project ID
    • PROJECT_NUMBER: the project account number

reCAPTCHA bot protection modes

reCAPTCHA bot protection has two modes that help you protect users: audit and enforce. These modes differ in behavior based on the identity provider.

Email-password provider

The audit and enforce modes behave as follows for email-password authentication flows.

Audit mode

When you set email-password enforcement to audit mode, Identity Platform creates one or more reCAPTCHA keys in your project that are used to assess traffic to Identity Platform APIs without blocking any requests. Use the metrics that are emitted during audit mode to determine if you should enable reCAPTCHA enforcement.

Enforce mode

When you set email-password enforcement to enforce mode, Identity Platform creates one or more reCAPTCHA keys in your project that are used to assess traffic to Identity Platform APIs. API requests that don't include a reCAPTCHA token are rejected. Only enable enforcement after you've migrated all your clients to an SDK with reCAPTCHA support.

Phone provider

The audit and enforce modes behave as follows for phone authentication flows.

Audit mode

When you set phone authentication enforcement to audit mode, Identity Platform uses reCAPTCHA bot protection for app verification. If the user request passes the bot protection assessment, Identity Platform sends an SMS message containing a verification code to the user's phone. If a request fails the bot protection 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 bot protection 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 bot protection 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 bot protection for app verification. If the user request passes the bot protection assessment, Identity Platform sends an SMS message containing a verification code to the user's phone. If the request fails the bot protection 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.

Set up the Identity Platform integration with the reCAPTCHA Enterprise API

To set up the Identity Platform integration with the reCAPTCHA Enterprise API, you perform the following tasks:

  • Use the Admin SDK to set the reCAPTCHA enforcement state and enable bot protection.
  • Configure the client SDK for your app's platform.

We recommend that you first enable reCAPTCHA enforcement in audit mode and monitor the reCAPTCHA metrics that your project emits to ensure that authentication flows are protected appropriately. You do this so that you don't interrupt your user traffic while you audit their use of reCAPTCHA. After you verify your authentication flows are protected, then set bot protection to ENFORCE.

Enable reCAPTCHA bot protection

Email-password provider

To enable reCAPTCHA bot protection for email-password authentication flows, do the following:

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

  2. To enable bot protection for a project, use the Admin SDK. reCAPTCHA support is available on Node.js Admin SDK versions 11.7.0 and later.

    For example:

    // Update project config with reCAPTCHA config
    const updateConfigRequest = {
      recaptchaConfig: {
        emailPasswordEnforcementState:  'ENFORCE_MODE',
        managedRules: [{
          endScore: END_SCORE,
          action: 'BLOCK'
        }]
      }
    };
    const updateProjectConfigWithRecaptcha = () => {
      getAuth().projectConfigManager().updateProjectConfig(updateConfigRequest).then((response) => {
        console.log('Updated reCAPTCHA config for project: ', response.recaptchaConfig);
      }).catch((error) => {
        console.log('Error updating project config:', error);
      });
    }
    

    Replace the following:

    • ENFORCE_MODE: the mode you want to set for reCAPTCHA email-password authentication enforcement. Valid values are OFF, AUDIT, and ENFORCE. To enable bot protection, this parameter must be set to AUDIT or ENFORCE. When you enable bot 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 bot protection modes.
    • END_SCORE: the lowest bot protection assessment score a request can have before it fails. You can set this score to be between 0.0 and 1.0. For example, if you set a threshold of 0.6, reCAPTCHA will fail any request with a 0.5 or lower. Therefore, the higher you set the score, the stricter the rules will be.

    You can also enable bot protection with the same config method for a tenant using the Admin SDK. For more information on updating a tenant, see Update a tenant.

  3. If you use Identity Platform on iOS or Android, you must register your app from the Firebase console:

    If you are using Identity Platform on the web, you must add an authorized domain for each domain that uses reCAPTCHA. To add authorized domains, do the following:

    1. In the Google Cloud console, go to the Identity Platform page.

      Go to Identity Platform

    2. Go to Settings > Security.

    3. Click Add domain.

    4. Enter the domain name and click Add to save the domain.

    reCAPTCHA key provisioning can take several minutes to complete.

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

Phone provider

To enable reCAPTCHA bot protection for SMS-based authentication flows, do the following:

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

  2. To enable bot protection for a project, use the Admin SDK. reCAPTCHA support is available on Node.js Admin SDK versions 12.7.0 and later.

    For example:

    // Update project config with reCAPTCHA config
    const updateProjectConfigRequest = {
      recaptchaConfig: {
        phoneEnforcementState: 'ENFORCE_MODE',
        managedRules: [{ endScore: END_SCORE, action: 'BLOCK' }],
        useSmsBotScore: 'true',
      }
    }
    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 bot protection for SMS-based flows, this parameter must be set to AUDIT or ENFORCE and useSmsBotScore must be set to true.

      When enabling bot 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 bot protection modes.

    • END_SCORE: the lowest bot protection assessment score a request can have before it fails. You can set this score to be between 0.0 and 1.0. For example, if you set a threshold of 0.6, reCAPTCHA will fail any request with a 0.5 or lower. Therefore, the higher you set the score, the stricter the rules will be.

    You can also enable bot protection with the same config method for a tenant using the Admin SDK. For more information on updating a tenant, see Update a tenant.

  3. If you are using Identity Platform on iOS or Android, you must register your app from the Firebase console:

    If you are using Identity Platform on the web, you must add an authorized domain for each domain that uses reCAPTCHA. To add authorized domains, do the following:

    1. In the Google Cloud console, go to the Identity Platform page.

      Go to Identity Platform

    2. Go to Settings > Security.

    3. Click Add domain.

    4. Enter the domain name and click Add to save the domain.

    reCAPTCHA key provisioning can take several minutes to complete.

  4. If you've set enforcement to audit mode, we recommend that you monitor the reCAPTCHA metrics for bot 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 bot 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 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. If reCAPTCHA key provisioning fails or if required service accounts weren't created, reCAPTCHA authentication attempts still succeed normally.

Ensure that reCAPTCHA authentication is working by examining the following metrics your project emits to Cloud Monitoring:

For more information, see Monitor reCAPTCHA metrics.

Enforce reCAPTCHA bot 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.

Email-password provider

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

const enforceRequest = {
  recaptchaConfig: {
    emailPasswordEnforcementState:  'ENFORCE',
    }]
  }
};

Phone provider

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

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

Disable reCAPTCHA bot protection

Email-password provider

To disable bot protection for email-password authentication flows, use the Admin SDK to run the following command:

const disableRequest = {
  recaptchaConfig: {
    emailPasswordEnforcementState:  'OFF',
  }
};

Phone provider

To disable bot protection for SMS-based authentication flows, use the Admin SDK to run the following command:

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

Overriding reCAPTCHA verdicts with Cloud Run functions

In addition to configuring score thresholds, you can override a reCAPTCHA verdict for a given token by using a custom Cloud Run functions blocking function. This is helpful in cases where a reCAPTCHA score for a given user login might be low, but the user is trusted or has been verified through other means and is therefore allowed to complete the sign-in.

To learn more about configuring blocking functions with reCAPTCHA, see Extend Firebase Authentication with blocking Cloud Functions.

What's next