Creating an assessment

When the end user triggers an HTML action, reCAPTCHA Enterprise sends an encrypted response, called the user's response token (token), to the end user's browser. For any type of site key integration (checkbox or score), you must create an assessment by submitting the generated token to the assessment endpoint. reCAPTCHA Enterprise processes the submitted token, and reports the token's validity and score.

This page explains how to retrieve the token and create an assessment.

Before you begin

Choose the best method for setting up reCAPTCHA Enterprise in your environment and complete the setup.

Retrieving the user's response token

Retrieve the user's response token from the web pages in one of following ways:

  • The resolved value of the promise returned by the call to grecaptcha.enterprise.execute().
  • g-recaptcha-response POST parameter when a user submits the form on your site.
  • As a string argument to your callback function if data-callback is specified in either the g-recaptcha HTML tag attribute or the callback parameter in the grecaptcha.enterprise.render method.

To retrieve user's response token from mobile applications, see Integrating reCAPTCHA Enterprise with iOS apps or Integrating reCAPTCHA Enterprise with Android apps.

You can access each user's reCAPTCHA response token only once. If you need to assess a subsequent action that a user takes on your site, or if a token expires before an assessment is created, you must call execute() again to generate a new token.

Creating an assessment

Create an assessment by sending a request to the reCAPTCHA Enterprise API, or by using the reCAPTCHA Enterprise Client Libraries. We recommend that you choose the method to create an assessment based on where you have set up reCAPTCHA Enterprise.

Choosing how to create an assessment

The methods you can use for creating an assessment depend on your environment:

Environment Methods for creating an assessment
Google Cloud App Engine or GKE reCAPTCHA Enterprise Client Libraries
Google Cloud Compute Engine

Either of the following:

  • reCAPTCHA Enterprise REST API, using the gcloud tool for authentication
  • reCAPTCHA Enterprise Client Libraries
Third-party cloud or on-premises that support service accounts

Either of the following:

  • reCAPTCHA Enterprise REST API, using the gcloud tool for authentication
  • reCAPTCHA Enterprise Client Libraries
Third-party cloud or on-premises that do not support service accounts reCAPTCHA Enterprise REST API, using API keys for authentication
Migrated environment using additional reCAPTCHA Enterprise features, such as Multi-factor authentication (MFA)

Either of the following:

  • reCAPTCHA Enterprise REST API, using the gcloud tool for authentication
  • reCAPTCHA Enterprise REST API, using API keys for authentication

Creating an assessment using the REST API or Client Libraries

After you select the appropriate method for creating an assessment, perform the following steps to create an assessment.

REST API

Create an assessment by sending a request to the reCAPTCHA Enterprise API. You can use either the gcloud tool or API key for authentication.

Authenticate with the gcloud tool

Create an assessment using the projects.assessments.create method. Send this request to the v1 API endpoint.

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

  • PROJECT_ID: your Google Cloud project ID
  • TOKEN: token returned from the grecaptcha.enterprise.execute() call
  • KEY: reCAPTCHA key associated with the site/app
  • USER_ACTION (for score-based site key integrations only): the user-initiated action that you specified for action in the grecaptcha.enterprise.execute() call, such as login. For more information, see Actions.

HTTP method and URL:

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

Request JSON body:

{
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY",
    "expectedAction": "USER_ACTION"
  }
}

To send your request, choose one of these options:

curl

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

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

PowerShell

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

$cred = gcloud auth application-default 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/assessments" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "tokenProperties": {
    "valid": true,
    "hostname": "www.google.com",
    "action": "homepage",
    "createTime": "2019-03-28T12:24:17.894Z"
   },
  "riskAnalysis": {
    "score": 0.1,
    "reasons": ["AUTOMATION"]
  },
 "event": {
    "token": "TOKEN",
    "siteKey": "KEY",
    "expectedAction": "USER_ACTION"
  },
  "name": "projects/PROJECT_ID/assessments/b6ac310000000000"
}

Authenticate with an API key

Create an assessment using the projects.assessments.create method. Send this request to the v1beta1 API endpoint.

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

  • API_KEY: API key associated with the current project
  • PROJECT_ID: your Google Cloud project ID
  • TOKEN: token returned from the grecaptcha.enterprise.execute() call
  • KEY: reCAPTCHA Key associated with the site/app
  • USER_ACTION (for score-based site key integrations only): the user-initiated action that you specified for action in the grecaptcha.enterprise.execute() call, such as login. For more information, see Actions.

HTTP method and URL:

POST https://recaptchaenterprise.googleapis.com/v1beta1/projects/PROJECT_ID/assessments?key=API_KEY

Request JSON body:

{
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY",
    "expectedAction": "USER_ACTION"
  }
}

To send your request, choose one of these options:

curl

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

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://recaptchaenterprise.googleapis.com/v1beta1/projects/PROJECT_ID/assessments?key=API_KEY"

PowerShell

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

$headers = @{  }

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

You should receive a JSON response similar to the following:

{
  "tokenProperties": {
    "valid": true,
    "hostname": "www.google.com",
    "action": "homepage",
    "createTime": "2019-03-28T12:24:17.894Z"
   },
  "score": 0.1,
  "reasons": ["AUTOMATION"],
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY",
    "expectedAction": "USER_ACTION"
  },
  "name": "projects/PROJECT_ID//assessments/b6ac310000000000"
}

C#

   using System;
   using Google.Api.Gax.ResourceNames;
   using Google.Cloud.RecaptchaEnterprise.V1;

   public class CreateAssessmentSample
   {
       // Create an assessment to analyze the risk of an UI action.
       // projectID: GCloud Project ID.
       // recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha.
       // token: The token obtained from the client on passing the recaptchaSiteKey.
       // recaptchaAction: Action name corresponding to the token.
       public void createAssessment(string projectID = "project-id", string recaptchaSiteKey = "recaptcha-site-key", 
           string token = "action-token", string recaptchaAction = "action-name")
       {
           // Specify a name for this assessment.
           string assessmentName = "your_assessment_name";

           // Create the client.
           RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.Create();

           ProjectName projectName = new ProjectName(projectID);

           // Build the assessment request.
           CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest()
           {
               Assessment = new Assessment()
               {
                   // Set the properties of the event to be tracked.
                   Event = new Event()
                   {
                       SiteKey = recaptchaSiteKey,
                       Token = token,
                       ExpectedAction = recaptchaAction
                   },
                   Name = assessmentName,
               },
               ParentAsProjectName = projectName
           };

           Assessment response = client.CreateAssessment(createAssessmentRequest);

           // Check if the token is valid.
           if (response.TokenProperties.Valid == false)
           { 
               System.Console.WriteLine("The CreateAssessment call failed because the token was: " +
                   response.TokenProperties.InvalidReason.ToString());
               return;
           }

           // Check if the expected action was executed.
           if (response.TokenProperties.Action != recaptchaAction)
           {
               System.Console.WriteLine("The action attribute in reCAPTCHA tag is: " + 
                   response.TokenProperties.Action.ToString());
               System.Console.WriteLine("The action attribute in the reCAPTCHA tag does not " +
                   "match the action you are expecting to score");
               return;
           }

           // Get the risk score and the reason(s).
           // For more information on interpreting the assessment,
           // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
           System.Console.WriteLine("The reCAPTCHA score is: " + ((decimal)response.RiskAnalysis.Score));

           foreach (RiskAnalysis.Types.ClassificationReason reason in response.RiskAnalysis.Reasons)
           {
               System.Console.WriteLine(reason.ToString());
           }
       }

       public static void Main(string[] args)
       {
           new CreateAssessmentSample().createAssessment();
       }
   }

Go

   import (
     "context"
     "fmt"

     recaptcha "cloud.google.com/go/recaptchaenterprise/apiv1"
     recaptchapb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1"
   )

   func main() {
     // TODO(developer): Replace these variables before running the sample.
     projectID := "project-id"
     recaptchaSiteKey := "recaptcha-site-key"
     token := "action-token"
     recaptchaAction := "action-name"
     assessmentName := "your-assessment-name"

     createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction, assessmentName)
   }

   /**
   * Create an assessment to analyze the risk of an UI action.
   *
   * @param projectID: GCloud Project ID
   * @param recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha services.
   * @param token: The token obtained from the client on passing the recaptchaSiteKey.
   * @param recaptchaAction: Action name corresponding to the token.
   */
   func createAssessment(projectID string, recaptchaSiteKey string, token string, recaptchaAction string, assessmentName string) {

     // Create the recaptcha client.
     ctx := context.Background()
     client, err := recaptcha.NewClient(ctx)
     if err != nil {
       fmt.Printf("Error creating reCAPTCHA client\n")
     }
     defer client.Close()

     // Set the properties of the event to be tracked.
     event := &recaptchapb.Event{
       Token:          token,
       SiteKey:        recaptchaSiteKey,
     }

     assessment := &recaptchapb.Assessment{
       Event: event,
       Name:  assessmentName,
     }

     // Build the assessment request.
     request := &recaptchapb.CreateAssessmentRequest{
       Assessment: assessment,
       Parent:     fmt.Sprintf("projects/%s", projectID),
     }

     response, err := client.CreateAssessment(
       ctx,
       request)

     if err != nil {
       fmt.Printf("%v", err.Error())
     }

     // Check if the token is valid.
     if response.TokenProperties.Valid == false {
       fmt.Printf("The CreateAssessment() call failed because the token"+
          " was invalid for the following reasons: %v",
       response.TokenProperties.InvalidReason)
       return
     }

     // Check if the expected action was executed.
     if response.TokenProperties.Action == recaptchaAction {
       // Get the risk score and the reason(s).
       // For more information on interpreting the assessment,
       // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
       fmt.Printf("The reCAPTCHA score for this token is:  %v",
         response.RiskAnalysis.Score)

       for _,reason := range response.RiskAnalysis.Reasons {
         fmt.Printf(reason.String()+"\n")
       }
       return
     }

     fmt.Printf("The action attribute in your reCAPTCHA tag does" +
         "not match the action you are expecting to score")
   }

Java

   import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
   import com.google.recaptchaenterprise.v1.Assessment;
   import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
   import com.google.recaptchaenterprise.v1.Event;
   import com.google.recaptchaenterprise.v1.ProjectName;
   import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason;
   import java.io.IOException;

   public class CreateAssessment {

     public static void main(String[] args) throws IOException {
       // TODO(developer): Replace these variables before running the sample.
       String projectID = "project-id";
       String recaptchaSiteKey = "recaptcha-site-key";
       String token = "action-token";
       String recaptchaAction = "action-name";

       createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction);
     }

     /**
      * Create an assessment to analyze the risk of an UI action.
      *
      * @param projectID: GCloud Project ID
      * @param recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha services.
      * @param token: The token obtained from the client on passing the recaptchaSiteKey.
      * @param recaptchaAction: Action name corresponding to the token.
      */
     public static void createAssessment(String projectID, String recaptchaSiteKey, String token,
         String recaptchaAction)
         throws IOException {
       // Initialize a client that will be used to send requests. This client needs to be created only
       // once, and can be reused for multiple requests. After completing all of your requests, call
       // the `client.close()` method on the client to safely
       // clean up any remaining background resources.
       try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

         // Specify a name for this assessment.
         String assessmentName = "assessment-name";

         // Set the properties of the event to be tracked.
         Event event = Event.newBuilder()
             .setSiteKey(recaptchaSiteKey)
             .setToken(token)
             .build();

         // Build the assessment request.
         CreateAssessmentRequest createAssessmentRequest = CreateAssessmentRequest.newBuilder()
             .setParent(ProjectName.of(projectID).toString())
             .setAssessment(Assessment.newBuilder().setEvent(event).setName(assessmentName).build())
             .build();

         Assessment response = client.createAssessment(createAssessmentRequest);

         // Check if the token is valid.
         if (!response.getTokenProperties().getValid()) {
           System.out.println("The CreateAssessment call failed because the token was: " +
              response.getTokenProperties().getInvalidReason().name());
           return;
         }

         // Check if the expected action was executed.
         if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {
           System.out.println("The action attribute in your reCAPTCHA tag " +
               "does not match the action you are expecting to score");
           return;
         }

         // Get the risk score and the reason(s).
         // For more information on interpreting the assessment,
         // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
         float recaptchaScore = response.getRiskAnalysis().getScore();
         System.out.println("The reCAPTCHA score is: " + recaptchaScore);

         for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
           System.out.println(reason);
         }
       }
     }
   }

Node.js

   /**
   * Create an assessment to analyze the risk of an UI action.
   *
   * projectID: GCloud Project ID
   * recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha services.
   * token: The token obtained from the client on passing the recaptchaSiteKey.
   * recaptchaAction: Action name corresponding to the token.
   * assessmentName: Set a name for this assessment.
   */
   function createAssessment() {
     let projectID = "project-id";
     let recaptchaSiteKey = "recaptcha-site-key";
     let token = "action-token";
     let recaptchaAction = "action-name";
     let assessmentName = "your_assessment_name";

     const {RecaptchaEnterpriseServiceClient} =
         require('@google-cloud/recaptcha-enterprise');

     // Create the reCAPTCHA client.
     const client = new RecaptchaEnterpriseServiceClient();

     // Set the properties of the event to be tracked.
     const event = ({
       token: token,
       siteKey: recaptchaSiteKey,
     });

     const assessment = ({
       event: event,
       name: assessmentName
     });

     const projectPath = client.projectPath(projectID)

     // Build the assessment request.
     const request = ({
       assessment: assessment,
       parent: projectPath
     });

     client.createAssessment(request, function (err, response) {
       // Check if the token is valid.
       if (!response.tokenProperties.valid) {
         console.log("The CreateAssessment call failed because the token was: " +
             response.tokenProperties.invalidReason);
       } else {
         // Check if the expected action was executed.
         if (response.tokenProperties.action === recaptchaAction) {
           // Get the risk score and the reason(s).
           // For more information on interpreting the assessment,
           // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
           console.log("The reCAPTCHA score is: " +
               response.riskAnalysis.score);

           // List classification reasons.
           response.riskAnalysis.reasons.forEach(function (reason) {
             console.log(reason);
           });
         } else {
           console.log("The action attribute in your reCAPTCHA tag " +
               "does not match the action you are expecting to score");
         }
       }
     });
   }

   createAssessment();

PHP

 <?php

   // Include Google Cloud dependencies using Composer
   require 'vendor/autoload.php';

   use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
   use Google\Cloud\RecaptchaEnterprise\V1\Event;
   use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
   use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;

   /**
   * Create an assessment to analyze the risk of a UI action.
   * @param string $siteKey The key ID for the reCAPTCHA key (See https://cloud.google.com/recaptcha-enterprise/docs/create-key)
   * @param string $token The user's response token for which you want to receive a reCAPTCHA score. (See https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#retrieve_token)
   * @param string $project Your Google Cloud project ID
   */
   function create_assessment(
      string $siteKey,
      string $token,
      string $project
   ): void {
      $client = new RecaptchaEnterpriseServiceClient();
      $projectName = $client->projectName($project);

      $event = (new Event())
          ->setSiteKey($siteKey)
          ->setToken($token);

      $assessment = (new Assessment())
          ->setEvent($event);

      try {
          $response = $client->createAssessment(
              $projectName,
              $assessment
          );

          // You can use the score only if the assessment is valid,
          // In case of failures like re-submitting the same token, getValid() will return false
          if ($response->getTokenProperties()->getValid() == false) {
              printf('The CreateAssessment() call failed because the token was invalid for the following reason: ');
              printf(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
          } else {
              printf('The score for the protection action is:');
              printf($response->getRiskAnalysis()->getScore());

              // Optional: You can use the following methods to get more data about the token
              // Action name provided at token generation.
              // printf($response->getTokenProperties()->getAction() . PHP_EOL);
              // The timestamp corresponding to the generation of the token.
              // printf($response->getTokenProperties()->getCreateTime()->getSeconds() . PHP_EOL);
              // The hostname of the page on which the token was generated.
              // printf($response->getTokenProperties()->getHostname() . PHP_EOL);
          }
      } catch (exception $e) {
          printf('CreateAssessment() call failed with the following error: ');
          printf($e);
      }
   }

   // TODO(Developer): Replace the following before running the sample
   create_assessment(
      'YOUR_RECAPTCHA_SITE_KEY',
      'YOUR_USER_RESPONSE_TOKEN',
      'YOUR_GOOGLE_CLOUD_PROJECT_ID'
   );

Python

  from google.cloud import recaptchaenterprise_v1

  def create_assessment():
     """ Create an assessment to analyze the risk of a UI action.

     Args:
     projectID: GCloud Project ID
     recaptchaSiteKey: Site key obtained by registering a domain/app to use recaptcha services.
     token: The token obtained from the client on passing the recaptchaSiteKey.
     recaptchaAction: Action name corresponding to the token.
     assessment_name: Specify a name for this assessment.
     """
     # TODO(developer): Replace these variables before running the sample.
     project_id = "your_project_id"
     recaptcha_site_key = "your_site_key"
     token = "action_token"
     recaptcha_action = "action_name"
     assessment_name = "assessment_name"

     client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

     # Set the properties of the event to be tracked.
     event = recaptchaenterprise_v1.Event()
     event.site_key = recaptcha_site_key
     event.token = token

     assessment = recaptchaenterprise_v1.Assessment()
     assessment.event = event
     assessment.name = assessment_name

     project_name = f'projects/{project_id}'

     # Build the assessment request.
     request = recaptchaenterprise_v1.CreateAssessmentRequest()
     request.assessment = assessment
     request.parent = project_name

     response = client.create_assessment(request)

     # Check if the token is valid.
     if not response.token_properties.valid:
         print("The CreateAssessment call failed because the token was " +
               "invalid for for the following reasons: "
               + str(response.token_properties.invalid_reason))
     else:
         # Check if the expected action was executed.
         if response.token_properties.action == recaptcha_action:
             # Get the risk score and the reason(s)
             # For more information on interpreting the assessment,
             # see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
             print("The reCAPTCHA score for this token is: " +
                   str(response.risk_analysis.score))
             for reason in response.risk_analysis.reasons:
                 print(reason)
         else:
             print("The action attribute in your reCAPTCHA tag does" +
                   "not match the action you are expecting to score")   

Ruby

  require "google/cloud/recaptcha_enterprise/v1"

  siteKey = "your_site_key"
  token = "user_response_token"
  parent_project = "projects/your_project_name"
  recaptcha_action = "name_of_action_to_protect"

  client = ::Google::Cloud::RecaptchaEnterprise::V1::RecaptchaEnterpriseService::Client.new

  event = ::Google::Cloud::RecaptchaEnterprise::V1::Event.new
  event.site_key = siteKey
  event.token = token
  event.expected_action = recaptcha_action

  assessment = ::Google::Cloud::RecaptchaEnterprise::V1::Assessment.new
  assessment.event = event

  request = ::Google::Cloud::RecaptchaEnterprise::V1::CreateAssessmentRequest.new
  request.parent = parent_project
  request.assessment = assessment

  response = client.create_assessment(request)

  if response.token_properties.valid == false
    printf("The CreateAssessment() call failed because the token was invalid with the following reason: %s ", response.token_properties.invalid_reason)
  else
    if response.event.expected_action == recaptcha_action
      printf("The reCAPTCHA score for this token is: %s" + response.risk+analysis.score)
    else
      printf("The action attribute in your reCAPTCHA tag does not match the action you are expecting to score")
    end
  end

What's next