Integrate with Google Cloud Armor for mobile applications

This document shows you how to integrate the WAF features of reCAPTCHA with Google Cloud Armor on mobile applications.

To complete the integration, you must implement one or more features of reCAPTCHA for WAF and configure Google Cloud Armor security policies. However, you can implement only reCAPTCHA action-tokens for integrating with Google Cloud Armor on mobile applications.

Before you begin

  1. Enable the reCAPTCHA Enterprise API.

    Enable the API

  2. Identify the actions that you want to protect.

Implement reCAPTCHA action-tokens

You must have reCAPTCHA running on your mobile application to generate action-tokens. After reCAPTCHA generates an action-token, you attach the action-token to a predefined request header wherever you need to protect any user action, such as checkout. By default, action-tokens are valid for 30 minutes, but can vary depending on the traffic. You must attach the action-token to a predefined request header before the token expires, so that the Google Cloud Armor can evaluate the token attributes.

To implement a reCAPTCHA action-token, do the following:

  1. Create an action-token key for your mobile application.

    Console

    1. In the Google Cloud console, go to the reCAPTCHA page.

      Go to reCAPTCHA

    2. Verify that the name of your project appears in the resource selector at the top of the page.

      If you don't see the name of your project, click the resource selector, then select your project.

    3. Click Create key.
    4. In the Display name field, enter a display name for the key.
    5. Depending on the type of application for which you want to create the reCAPTCHA keys for WAF, perform the appropriate action:
    6. Create reCAPTCHA keys for WAF for iOS applications

      We recommend creating one reCAPTCHA key per iOS application.

      1. From the Choose platform type menu, select iOS app.
        1. In the iOS bundle ID list section, click Add iOS bundle ID.
        2. In the Bundle ID field, enter the name of your iOS bundle ID.

        3. Optional: To add an additional bundle ID, click Add iOS bundle ID and enter the name of your iOS bundle ID in the Bundle ID field.
        4. Optional: Provide Apple Developer settings.

          We recommend providing this data because it allows reCAPTCHA to provide more accurate risk scores for your traffic.

          Enter the following information:

          • Private key (.p8): This is generated in the Apple Developer Center under Certificates, Identifiers & Profiles.
          • Key identifier: The Apple developer key identifier (10-character string).
          • Team ID: The Apple team ID (10-character string) owning the provisioning profile that is used to build your application.
        5. Expand Bundle ID verification and key type.
          1. To create a reCAPTCHA key for WAF, do the following:
            1. Turn on the Web application firewall (WAF) toggle.
            2. From the Service menu, select Cloud Armor.
            3. From the Feature menu, select Action token.
          2. To protect the reCAPTCHA key for your bundle IDs, ensure that the Disable bundle ID verification toggle is turned off.
          3. For your non-production environment, if you want to specify a score that you want the key to return when any assessments are created for it, do the following:

            1. Click the This is a testing key toggle.
            2. In the Score box, specify a score between 0 to 1.0.
        6. Click Create key.
        7. The newly created key is listed on the reCAPTCHA keys page.

      Create reCAPTCHA keys for WAF for Android applications

      1. From the Choose platform type menu, select Android app.
      2. In the Android package list section, click Add Android package.
      3. In the Android package field, enter the name of your Android package.
      4. Optional: To add an additional package, click Add Android package and enter the name of another Android package in the Android package field.
      5. Expand Package name verification, app distribution, and testing keys.
        1. To create a reCAPTCHA key for WAF, do the following:
          1. Turn on the Web application firewall (WAF) toggle.
          2. From the Service menu, select Cloud Armor.
          3. From the Feature menu, select Action token.
        2. To enforce that reCAPTCHA key is only used within your app, turn off the Disable package name verification toggle.
        3. If you want to create a key for an application that is available on other app stores in addition to the Google Play Store, turn on Support applications distributed outside of the Google Play Store.
        4. For your non-production environment, if you want to specify a score that you want the key to return when any assessments are created for it, do the following:

          1. Click the This is a testing key toggle.
          2. In the Score box, specify a score between 0 to 1.0.
      6. Click Create key.
      7. The newly created key is listed on the reCAPTCHA keys page.

    gcloud (iOS)

    To create reCAPTCHA keys, use the gcloud recaptcha keys create command.

    Before using any of the command data below, make the following replacements:

    • DISPLAY_NAME: Name for the key. Typically a site name.
    • BUNDLE_IDs: iOS bundle ids of apps allowed to use the key. Specify multiple bundle IDs as a comma-separated list.
    • WAF_FEATURE: Name of the WAF feature. Specify action-token.
    • WAF_SERVICE: Name of the WAF service provider. Specify CA for Google Cloud Armor.

    Execute the gcloud recaptcha keys create command:

    Linux, macOS, or Cloud Shell

    
    gcloud recaptcha keys create \
    --display-name=DISPLAY_NAME  \
    --ios --bundle-ids=BUNDLE_IDs \
    --waf-feature=WAF_FEATURE \
    --waf-service=WAF_SERVICE 
    

    Windows (PowerShell)

    
    gcloud recaptcha keys create `
    --display-name=DISPLAY_NAME  `
    --ios --bundle-ids=BUNDLE_IDs `
    --waf-feature=WAF_FEATURE `
    --waf-service=WAF_SERVICE 
    

    Windows (cmd.exe)

    
    gcloud recaptcha keys create ^
    --display-name=DISPLAY_NAME  ^
    --ios --bundle-ids=BUNDLE_IDs ^
    --waf-feature=WAF_FEATURE ^
    --waf-service=WAF_SERVICE 
    

    The response contains the newly created reCAPTCHA key.

    gcloud (Android)

    To create reCAPTCHA keys, use the gcloud recaptcha keys create command.

    Before using any of the command data below, make the following replacements:

    • DISPLAY_NAME: Name for the key. Typically a site name.
    • PACKAGE_NAMES: Android package names of apps allowed to use the key. Specify multiple package names as a comma-separated list.
    • WAF_FEATURE: Name of the WAF feature. Specify action-token.
    • WAF_SERVICE: Name of the WAF service provider. Specify CA for Google Cloud Armor.

    Execute the gcloud recaptcha keys create command:

    Linux, macOS, or Cloud Shell

    
    gcloud recaptcha keys create \
    --display-name=DISPLAY_NAME  \
    --android --package-names=PACKAGE_NAMES \
    --waf-feature=WAF_FEATURE \
    --waf-service=WAF_SERVICE 
    
    

    Windows (PowerShell)

    
    gcloud recaptcha keys create `
    --display-name=DISPLAY_NAME  `
    --android --package-names=PACKAGE_NAMES `
    --waf-feature=WAF_FEATURE `
    --waf-service=WAF_SERVICE 
    
    

    Windows (cmd.exe)

    
    gcloud recaptcha keys create ^
    --display-name=DISPLAY_NAME  ^
    --android --package-names=PACKAGE_NAMES ^
    --waf-feature=WAF_FEATURE ^
    --waf-service=WAF_SERVICE 
    
    

    The response contains the newly created reCAPTCHA key.

    REST (iOS)

    Before using any of the request data, make the following replacements:

    • DISPLAY_NAME: Name for the key. Typically an app name.
    • BUNDLE_IDs: iOS bundle ids of apps allowed to use the key. Specify multiple bundle IDs as a comma-separated list.
    • WAF_FEATURE: Name of the WAF feature. Specify action-token.
    • WAF_SERVICE: Name of the WAF service provider. Specify CA for Google Cloud Armor.

    HTTP method and URL:

    POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys

    Request JSON body:

    {
      "displayName": "DISPLAY_NAME",
      "iosSettings": {
     "allowedBundleIds": "BUNDLE_IDS"
     },
       'wafSettings': "  {
           "wafService": "CA",
     "wafFeature": "ACTION_TOKEN"
      }
     }
    
    

    To send your request, choose one of these options:

    curl

    Save the request body in a file named request.json, and execute the following command:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys"

    PowerShell

    Save the request body in a file named request.json, and execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    
    {
      "name": "projects/project-id/keys/6LfhtywnAAAAABY3sCS2duZ6A55kmDXz-PNEgKgT",
      "displayName": "DISPLAY_NAME",
      "iosSettings": {
        "allowAllBundleIds": false,
        "allowedBundleIds": [
            BUNDLE_IDS
        ]
      },
      "labels": {},
      "wafSettings": {
          "wafService": "CA",
          "wafFeature": "ACTION_TOKEN"
      }
    }
    
    

    REST (Android)

    Before using any of the request data, make the following replacements:

    • DISPLAY_NAME: Name for the key. Typically an app name.
    • PACKAGE_NAMES: Android package names of apps allowed to use the key. Specify multiple package names as a comma-separated list.
    • WAF_FEATURE: Name of the WAF feature. Specify action-token.
    • WAF_SERVICE: Name of the WAF service provider. Specify CA for Google Cloud Armor.

    HTTP method and URL:

    POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys

    Request JSON body:

    {
      "displayName": "DISPLAY_NAME",
      "androidSettings": {
      "allowedPackageNames":"PACKAGE_NAMES"
     },
       'wafSettings': "  {
           "wafService": "CA",
     "wafFeature": "ACTION_TOKEN"
      }
     }
    
    

    To send your request, choose one of these options:

    curl

    Save the request body in a file named request.json, and execute the following command:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys"

    PowerShell

    Save the request body in a file named request.json, and execute the following command:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/keys" | Select-Object -Expand Content

    You should receive a JSON response similar to the following:

    
    {
      "name": "projects/project-id/keys/6LcioSknAAAAABrjlMuZv2fjIGYMqwaAFC9izhoy",
      "displayName": "DISPLAY_NAME",
      "androidSettings": {
          "allowAllPackageNames": false,
          "allowedPackageNames": [
              PACKAGE_NAMES
          ],
          "supportNonGoogleAppStoreDistribution": false
      },
      "labels": {},
      "wafSettings": {
          "wafService": "CA",
          "wafFeature": "ACTION_TOKEN"
      }
    }
    
    

  2. Integrate reCAPTCHA mobile SDK on your mobile applications with the action-token key that you created. For instructions, refer to the document that corresponds with the type of your mobile application.

  3. After you receive the token from reCAPTCHA, attach the token to a predefined request header in the following format:

    X-Recaptcha-Token: value-of-your-action-token
    

    The following sample code shows how to attach the token:

    Android

    Sample code in Java

    
    // This example shows how to send an HTTP request to the backend server
    // attached with the reCAPTCHA token in the header.
    //
    // @param serverUrl: the URL of the backend server.
    // @param rceToken: reCAPTCHA token that is attached to the header of the
    // HTTP request.
    
    public static void sendRequestToServerWithRceToken(
        String serverUrl, String rceToken) throws JSONException, IOException {
     URL url = new URL(String.format("http://%s/decryptcaptchacookie/accesswafserver", serverUrl));
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setRequestProperty("X-Recaptcha-Token", rceToken);
    
     try {
        String requestBody = "['']";
        sendRequest(connection, requestBody, "AccessWithRceToken", "GET");
     } finally {
        connection.disconnect();
     }
    }
    
    private static void sendRequest(
        HttpURLConnection connection, String requestString, String requestName, String action)
        throws IOException {
     connection.setConnectTimeout(HTTP_CONNECT_TIMEOUT_MS);
     connection.setReadTimeout(HTTP_READ_TIMEOUT_MS);
     connection.setRequestProperty("Content-type", CONTENT_TYPE);
     connection.setRequestProperty(
        "Content-Length", Integer.toString(Utf8.encodedLength(requestString)));
     connection.setRequestMethod(action);
     connection.setDoOutput(true);
     connection.connect();
     try (OutputStream postStream = connection.getOutputStream()) {
        postStream.write(requestString.getBytes(UTF_8));
     }
    
     int responseCode = connection.getResponseCode();
     String response = connection.getResponseMessage();
     if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException(
           String.format(
              "Failed to complete request.\nResponse code:%s\nError Detail:\n%s",
              responseCode, response));
     }
    }
    
    

    iOS

    Sample code in Swift

    
    // This example shows how to send an HTTP request to the backend server
    // attached with the reCAPTCHA token in the header.
    // @param serverUrl: the URL of the backend server.
    // @param rceToken: reCAPTCHA token that is attached to the header of
    // the HTTP request.
    
     public static func accessWafServer(rceToken: String, serverUrl: String)
        async throws -> String
     {
        let requestURL = try HttpHelper.createRequestURL(endpoint: serverUrl)
        var request = try HttpHelper.createRequest(requestURL: requestURL, action: "GET")
        request.setValue(rceToken, forHTTPHeaderField: "X-Recaptcha-Token")
    
        let data = try await HttpHelper.getDataFromServer(request)
    
        return String(decoding: data, as: UTF8.self)
     }
    
    

Configure Google Cloud Armor security policies

After implementing the features of reCAPTCHA for WAF, you must configure Google Cloud Armor security policies that evaluates reCAPTCHA tokens for bot management.

To learn how to configure Google Cloud Armor security policies and use the action-token keys with your security policies, see Configure rules for bot management.

What's next