Enable reCAPTCHA Enterprise

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

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

Overview

When you configure Identity Platform integration with reCAPTCHA Enterprise, Identity Platform provisions score-based reCAPTCHA Enterprise site 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 Enterprise:

Operation Method
Email and password sign in signInWithPassword
Email and password sign up signUpPassword
Email link sign in getOobCode
Password reset getOobCode

reCAPTCHA then provides Identity Platform with risk signals that assess the risk of the request based on your configuration and risk tolerance.

For more information, see Overview of reCAPTCHA Enterprise.

Before you begin

Configure email sign-in for users.

Create a service account

Before you enable reCAPTCHA Enterprise, you must create a service account for each project that will use reCAPTCHA and grant each service account access to reCAPTCHA Enterprise. This allows Identity Platform to manage reCAPTCHA keys on your behalf.

To create a service account, 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 Enterprise:

    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

Enable reCAPTCHA Enterprise

reCAPTCHA has two modes that help you protect users:

  • Audit: When enabled, Identity Platform creates one or more reCAPTCHA Enterprise keys in your project that are used to assess traffic to Identity Platform APIs without blocking any requests. Use the metrics emitted during audit mode to determine if you should enable reCAPTCHA enforcement.
  • Enforcement: When enabled, Identity Platform creates one or more reCAPTCHA Enterprise 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 Enterprise support.

To enable reCAPTCHA Enterprise, do the following:

  1. If you have not already done so, enable the reCAPTCHA Enterprise API on your project.
  2. Enable Identity Platform integration with reCAPTCHA Enterprise for a project using the admin SDK. reCAPTCHA Enterprise support is available on Node.js admin SDK versions 11.7.0 and above.

    For example:

    // Get project config
    const getProjectConfig = () => {
      getAuth().projectConfigManager().getProjectConfig()
      .then((response) => {
        console.log('Project reCAPTCHA config: ', response.recaptchaConfig);
      }).catch((error) => {
        console.log('Error getting project config:', error);
      });
    }
    
    // Update project config with reCAPTCHA config
    const updateConfigRequest = {
      recaptchaConfig: {
        emailPasswordEnforcementState:  'AUDIT',
        managedRules: [{
          endScore: 0.3,
          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);
      });
    }
    
  3. Enable Identity Platform integration with reCAPTCHA Enterprise for a tenant using the admin SDK. For example:

    // Update tenant with reCAPTCHA config
    const updateTenantRequest = {
      recaptchaConfig: {
        emailPasswordEnforcementState:  'AUDIT',
        managedRules: [{
          endScore: 0.3,
          action: 'BLOCK'
        }]
      }
    };
    const updateTenantWithRecaptchaConfig = () => {
      getAuth().tenantManager().updateTenant("TENANT_ID", updateTenantRequest)
      .then((response) => {
        console.log('Updated reCAPTCHA config for tenant: ', response.recaptchaConfig);
      }).catch((error) => {
        console.log('Error updating the tenant:', error);
      });
    }
    

    Replace the following:

    • TENANT_ID: the tenant ID
  4. If you are using Identity Platform on Apple platforms or Android, you must register your app from the Firebase console:

  5. If you are using Identity Platform on 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.

    Site key provisioning can take several minutes to complete. To ensure that your flows are being protected, check the metrics.

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 Enterprise support is available on JavaScript SDK versions 9.20.0 and above. After you've integrated the web SDK with your app, it automatically fetches your reCAPTCHA Enterprise configuration and protects 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 Auth
    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 Android SDK version 31.5.0 or later. reCAPTCHA Enterprise support requires API level 19 (KitKat) or higher and Android 4.4 or higher. After you've integrated the Android SDK with your app, it automatically fetches your reCAPTCHA Enterprise configuration and protects 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.4.0'
    

    Make sure to use reCAPTCHA SDK version 18.4.0 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 Auth
    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 Auth
    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

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

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

  3. Ensure that -ObjC is listed on 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 Auth
    try await Auth.auth().initializeRecaptchaConfig()
    
    • Objective-C:
    // Initialize Firebase Auth
    [[FIRAuth auth] initializeRecaptchaConfigWithCompletion:^(NSError * _Nullable error) {
      // Firebase Auth initialization finished
    }];
    

reCAPTCHA Enterprise metrics

After you enable reCAPTCHA Enterprise, monitor the reCAPTCHA metrics your project emits to ensure that authentication flows are protected. If reCAPTCHA site key provisioning fails or if required service accounts weren't created, reCAPTCHA authentication fails open.

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

identitytoolkit.googleapis.com/recaptcha/verdict_count

Tracks the different verdicts returned by reCAPTCHA Enterprise. A verdict is generated if a token is present. You can filter on the following verdicts:

  • PASSED: Indicates that a given request is allowed when enforcement is enabled.
  • FAILED_AUDIT: Indicates that a given request is denied when reCAPTCHA audit mode is enabled.
  • FAILED_ENFORCE: Indicates that a given request is denied when reCAPTCHA enforcement mode is enabled.
  • CLIENT_TYPE_MISSING: Indicates that a given request has a missing client type when reCAPTCHA enforcement is enabled. This typically occurs if a request was sent using an outdated Client SDK version that does not have reCAPTCHA support.
  • KEYS_MISSING: Indicates that a given request can't be verified due to the inability to retrieve or generate valid reCAPTCHA keys when reCAPTCHA enforcement is enabled.

To modify your score ranges to change the ratio of passed-to-failed verdicts, see Enable reCAPTCHA Enterprise.

identitytoolkit.googleapis.com/recaptcha/token_count

Tracks the number and status of reCAPTCHA Enterprise tokens received by the Identity Platform backend. You can filter on the following statuses:

  • VALID: Indicates that the reCAPTCHA token passed in is valid.
  • EXPIRED: Indicates that the reCAPTCHA token passed in has expired. An expired token might indicate client network issues or abuse.
  • DUPLICATE: Indicates that the reCAPTCHA token passed in is a duplicate. A duplicate token might indicate client network issues or abuse.
  • INVALID: Indicates that the reCAPTCHA token passed in is invalid. An invalid token might indicate abuse.
  • MISSING: Indicates that the reCAPTCHA token doesn't exist in the given request. Missing tokens might indicate an outdated client app.
  • UNCHECKED: Indicates that the reCAPTCHA token was not checked due to CLIENT_TYPE_MISSING or KEYS_MISSING verdicts.

If your app rolled out successfully to users, you will see traffic with valid tokens. The number of valid tokens is likely proportional to the number of users who are using your updated app.

identitytoolkit.googleapis.com/recaptcha/risk_scores

Tracks the reCAPTCHA score distribution. This can help you define the optimal score ranges for your configuration.

Use these metrics to determine if you can enable enforcement. You should consider the following before enabling enforcement:

  • If the majority of recent requests have valid tokens and the ratio of PASSED to FAILED_AUDIT or FAILED_ENFORCE verdicts is acceptable for your business case, consider enabling enforcement.
  • If a majority of the recent requests are likely from outdated clients, consider waiting for more users to update their app before enabling enforcement. Enforcing Identity Platform integration with reCAPTCHA Enterprise breaks prior app versions that are not integrated with reCAPTCHA Enterprise.

To view these metrics, do the following:

  1. In the Google Cloud console, go to the Metrics explorer page.

    Go to Metrics explorer

  2. From Select a metric, enter Identity Toolkit Tenant. If you are using multi-tenancy, you can view metrics for each tenant, as well as the parent project, by leaving tenant_name empty.

Enable enforcement

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 a project or tenant, use the admin SDK to run the following:

const enforceRequest = {
  recaptchaConfig: {
    emailPasswordEnforcementState:  'ENFORCE',
    managedRules: [{
      endScore: 0.3,
      action: 'BLOCK'
    }]
  }
};

Disable reCAPTCHA Enterprise

To disable reCAPTCHA Enterprise, use the admin SDK to run the following:

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

Overriding reCAPTCHA Enterprise verdicts with Cloud Functions

In addition to configuring score thresholds, you can override a reCAPTCHA Enterprise verdict for a given token by using a custom Cloud 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 Enterprise, see Extend Firebase Authentication with blocking Cloud Functions.

Troubleshooting

Users are unable to log in, sign up, or reset their password

Users might be using an outdated version of the app. If you have not provided an updated version of your app that uses the Client SDK, turn off enforcement mode immediately. Otherwise, ask your users to update their app.

Alternatively, users might be blocked based on your current configuration. Try the following:

  • Consider a more permissive configuration by adjusting. reCAPTCHA key scores.
  • Ask the user to try a different device, browser, or network.
  • Revert to audit mode and monitor metrics before re-enabling enforcement mode.