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:

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. \
        --role=roles/identitytoolkit.serviceAgent
    

    Replace the following:

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

reCAPTCHA bot protection behavior by provider

reCAPTCHA bot protection behavior depends on the identity provider you configure:

Email-password provider

For email-password authentication flows, reCAPTCHA bot protection supports two modes: audit and enforce.

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

When you enable bot protection for phone authentication flows by setting phoneEnforcementState to ENFORCE and useSmsBotScore to true, Identity Platform uses reCAPTCHA bot protection for app verification. If a user's request passes the bot protection assessment, an SMS verification code is sent. If a user's request fails the bot protection assessment, Identity Platform blocks the request and doesn't send an SMS message containing a verification code.

Fallback verification is not required when bot protection is enabled for phone authentication flows, and you don't have to set up any additional verification methods for your app. However, we recommend setting up the reCAPTCHA verifier for web apps to ensure that reCAPTCHA v2 is available if you decide to disable bot protection.

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.

For email-password authentication flows, we recommend that you first enable reCAPTCHA enforcement in the audit mode and monitor the reCAPTCHA metrics that your project emits to avoid interrupting user traffic while verifying that authentication flows are protected. After you verify your authentication flows are protected, then set bot protection to ENFORCE. For phone authentication flows, enable bot protection by setting phoneEnforcementState to ENFORCE and useSmsBotScore to true, and monitor the reCAPTCHA metrics to fine-tune your score thresholds.

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 behavior by provider.
    • 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',
        managedRules: [{
          endScore: END_SCORE,
          action: 'BLOCK'
        }],
        useSmsBotScore: true,
      }
    };
    let projectConfig = await getAuth().projectConfigManager().updateProject(updateProjectConfigRequest);
    

    Replace END_SCORE with 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 fails any request with a 0.5 or lower. Therefore, the higher you set the score, the stricter the rules are.

    Setting phoneEnforcementState to ENFORCE and useSmsBotScore to true enables bot protection enforcement for SMS-based authentication flows. For more information on how phone provider enforcement works, see reCAPTCHA bot protection behavior by provider.

    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. 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. If needed, you can force fetch the reCAPTCHA signal 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. If needed, you can force fetch the reCAPTCHA signal 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

  1. Update to iOS SDK version 11.6.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. If needed, you can force fetch the reCAPTCHA signal 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

Monitor the reCAPTCHA metrics your project emits to ensure that authentication flows are protected. For email-password authentication flows, we recommend monitoring metrics in audit mode before setting enforcement to enforce mode. 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 for email-password flows

For email-password authentication flows that you initially configured in AUDIT mode, after you verify that your app is receiving acceptable user traffic, you can switch emailPasswordEnforcementState to ENFORCE to block requests that fail the reCAPTCHA assessment. Ensure you don't disrupt existing users, including users who might be using an older version of your app.

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

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

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 all phone reCAPTCHA protection, including bot protection, for SMS-based authentication flows, use the Admin SDK to run the following command:

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

If you are also using reCAPTCHA SMS defense and want to keep it enabled while disabling bot protection, set useSmsBotScore to false and leave phoneEnforcementState set to ENFORCE:

const disableBotScoreOnlyRequest = {
  recaptchaConfig: {
    phoneEnforcementState: 'ENFORCE',
    useSmsBotScore: false,
    useSmsTollFraudProtection: true
  }
};

Override reCAPTCHA verdicts with Cloud Run functions

In addition to configuring score thresholds, you can override a reCAPTCHA verdict for a given token by using blocking functions to allow or block flows based on custom factors. 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.

The following example shows how to override a reCAPTCHA verdict by using blocking functions:

Node.js

  const functions = require("firebase-functions/v1");
  exports.beforesmsv1 = functions.auth.user().beforeSms((context) => {
    if (
      context.smsType === "SIGN_IN_OR_SIGN_UP" &&
      context.additionalUserInfo.phoneNumber.includes('+91')
    ) {
      return {
        recaptchaActionOverride: "ALLOW",
      };
    }

    // Allow users to sign in with recaptcha score greater than 0.5
    if (event.additionalUserInfo.recaptchaScore > 0.5) {
      return {
        recaptchaActionOverride: 'ALLOW',
      };
    }

    // Block all others.
    return  {
      recaptchaActionOverride: 'BLOCK',
    }
  });

What's next