Creating an assessment

This page explains how to assess a user's reCAPTCHA response token from your application's backend.

For any type of site key integration (checkbox or score), you must submit the generated token to the assessment endpoint. reCAPTCHA Enterprise processes this token and reports the token's validity and score.

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

Creating an assessment using the REST API or Client Libraries

After you select the appropriate method for creating an assessment, follow these 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 below, 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: 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 below, make the following replacements:

  • API_KEY: API key associated with the current project
  • PROJECT_ID: your GCP project ID
  • TOKEN: token returned from the grecaptcha.enterprise.execute() call
  • KEY: reCAPTCHA Key associated with the site/app
  • USER_ACTION: 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.Cloud.RecaptchaEnterprise.V1;

namespace csharp_recaptcha_sample
{
    public class create_assessment_sample
    {
        static void Main(string[] args)
        {

            string SiteKey = "your_site_key";
            string Token = "your_token";
            string AssessmentName = "your_assessment_name";
            string ParentProject = "projects/your_project_name";
            string RecaptchaAction = "name_of_action_to_protect";

            RecaptchaEnterpriseServiceClient client =
                RecaptchaEnterpriseServiceClient.Create();

            CreateAssessmentRequest createAssessmentRequest = new CreateAssessmentRequest()
            {
                Assessment = new Assessment()
                {
                    Event = new Event()
                    {
                        SiteKey = SiteKey,
                        Token = Token,
                        ExpectedAction = RecaptchaAction
                    },
                    Name = AssessmentName,
                },
                Parent = ParentProject
            };

            Assessment response = client.CreateAssessment(createAssessmentRequest);

            if (response.TokenProperties.Valid == false)
            {
                System.Console.WriteLine("The CreateAssessment() call failed " +
                    "because the token was invalid for the following reason: " +
                    response.TokenProperties.InvalidReason.ToString());
            }
            else
            {
                if (response.Event.ExpectedAction == RecaptchaAction)
                {
                    System.Console.WriteLine("The reCAPTCHA score for this token is: " +
                        response.RiskAnalysis.Score.ToString());
                }
                else
                {
                    System.Console.WriteLine("The action attribute in your reCAPTCHA " +
                        "tag does not match the action you are expecting to score");

                }

            }

        }
    }
}

Go

package main

import (
  "context"
  "fmt"

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

func main() {

  siteKey := "your_sitekey"
  token := "your_token"
  assessmentName := "your_assessment_name"
  parentProject := "projects/your_project_name"
  recaptchaAction := "name_of_action_to_protect"

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

  event := &recaptchapb.Event{
    ExpectedAction: recaptchaAction,
    Token:          token,
    SiteKey:        siteKey,
  }

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

  request := &recaptchapb.CreateAssessmentRequest{
    Assessment: assessment,
    Parent:     parentProject,
  }

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

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

  if response.TokenProperties.Valid == false {
    fmt.Printf("The CreateAssessment() call failed because the token"+
      " was invalid for the following reasons: %v",
      response.TokenProperties.InvalidReason)
  } else {
    if response.Event.ExpectedAction == recaptchaAction {
      fmt.Printf("The reCAPTCHA score for this token is:  %v",
        response.RiskAnalysis.Score)
    } else {
      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.*;
  import com.google.recaptchaenterprise.v1.Assessment;
  import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
  import com.google.recaptchaenterprise.v1.Event;
  import java.io.IOException;

  public class test1 {
      public static void main(String[] args) throws IOException {

          String siteKey = "your_site_key";
          String token = "your_token";
          String assessmentName = "assessment_name";
          String projectPath = "projects/your_project_name";
          String recaptchaAction = "name_of_action_to_protect";

          RecaptchaEnterpriseServiceClient client =
                  RecaptchaEnterpriseServiceClient.create();

          Event event =
                  Event.newBuilder()
                          .setToken(token)
                          .setSiteKey(siteKey)
                          .setExpectedAction(recaptchaAction)
                          .build();

          Assessment assessment =
                  Assessment.newBuilder()
                          .setEvent(event)
                          .setName(assessmentName)
                          .build();

          CreateAssessmentRequest createAssessmentRequest =
                  CreateAssessmentRequest.newBuilder()
                          .setParent(projectPath)
                          .setAssessment(assessment)
                          .build();

          Assessment response =
                  client.createAssessment(createAssessmentRequest);

          if (!response.getTokenProperties().getValid()) {
              System.out.println("The CreateAssessment call failed because the token was: " +
                      response.getTokenProperties().getInvalidReason().name());
          } else {
              if (response.getEvent().getExpectedAction() == recaptchaAction) {
                  System.out.println("The reCAPTCHA score is: " +
                          response.getRiskAnalysis().getScore());
              } else {
                  System.out.println("The action attribute in your reCAPTCHA tag " +
                          "does not match the action you are expecting to score");
              }
          }
      }
  }

Node.js

    function main() {

    let siteKey = "your_site_key";
    let token = "your_token";
    let assessmentName = "your_assessment_name";
    let parentPath = "projects/your_project_name";
    let recaptchaAction = "name_of_action_to_protect";

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

    const event = ({
        token: token,
        siteKey: siteKey,
        protectedAction: recaptchaAction
    });

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

    const request = ({
        assessment: assessment,
        parent: parentPath
    });

    client.createAssessment(request, function(err, response) {

        if (response.tokenProperties.valid == false)
        {
            console.log("The CreateAssessment() call failed because the " +
                "token was invalid with the following reason: " +
                response.tokenProperties.invalidReason);
        }
        else
        {
            if (response.event.expectedAction == protectedAction){
                console.log("The reCAPTCHA score is: " +
                    response.riskAnalysis.score);
            }
            else
            {
                console.log("The action attribute in your reCAPTCHA tag does " +
                    "not match the action you are expecting to score");
            }
        }
    });
}

main();

PHP

 <?php
 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;

 $client = new RecaptchaEnterpriseServiceClient();

 define('SITE_KEY', 'your_site_key');
 define('TOKEN', 'your_token');
 define('ASSESSMENT_NAME', 'your_assessment_name');
 define('PROTECTED_ACTION', 'name_of_action_to_protect');
 define('PARENT_PROJECT', 'projects/your_project_name');

 $event = (new Event())
     ->setSiteKey(SITE_KEY)
     ->setExpectedAction(PROTECTED_ACTION)
     ->setToken(TOKEN);

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

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

     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 {
         if ($response->getEvent()->getExpectedAction() == PROTECTED_ACTION) {
             printf('The score for the protection action is:');
             printf($response->getRiskAnalysis()->getScore());
         }
         else
         {
             printf('The action attribute in your reCAPTCHA tag does not match the action you are expecting to score');
         }
     }
 } catch (exception $e) {
     printf('CreateAssessment() call failed with the following error: ');
     printf($e);
 }

Python

  from google.cloud import recaptchaenterprise_v1

  site_key = "your_site_key"
  token = "your_token"
  assessment_name = "your_assessment_name"
  parent_project = "projects/your_project_name"
  recaptcha_action = "name_of_action_to_protect"

  client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

  event = recaptchaenterprise_v1.Event()
  event.site_key = site_key
  event.token = token
  event.expected_action = recaptcha_action

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

  request = recaptchaenterprise_v1.CreateAssessmentRequest()
  request.assessment = assessment
  request.parent = parent_project

  response = client.create_assessment(request)

  if not response.token_properties.valid:
    print("The CreateAssessment() call failed because the token was " +
          "invalid for the following reasons: "
          + str(response.token_properties.invalid_reason))
  else:
    if response.event.expected_action == recaptcha_action:
      print("The reCAPTCHA score for this token is: " +
            str(response.risk_analysis.score))
    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 = "your_token"
  assessment_name = "your_assessment_name"
  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
  assessment.name = assessment_name

  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