创建评估

本页面介绍了如何从应用的后端评估用户的 reCAPTCHA 响应令牌。

对于任何类型的网站密钥集成(复选框或得分),您必须将生成的令牌提交到评估端点。reCAPTCHA Enterprise 会处理提交的令牌,并报告令牌的有效性和得分。

准备工作

选择在您的环境中设置 reCAPTCHA Enterprise 的最佳方法,并完成设置。

检索用户的响应令牌

通过下列任一方式从网页中检索用户的响应令牌:

  • 调用 grecaptcha.enterprise.execute() 返回的 promise 的解析值。
  • 用户在您的网站上提交表单时的 g-recaptcha-response POST 参数。
  • 作为回调函数的字符串参数(如果在 g-recaptcha HTML 标记属性中或在 grecaptcha.enterprise.render 方法中的回调参数中指定了 data-callback)。

要从移动应用检索用户的响应令牌,请参阅将 reCAPTCHA Enterprise 与 iOS 应用集成将 reCAPTCHA Enterprise 与 Android 应用集成

您只能访问每个用户的 reCAPTCHA 响应令牌一次。如果您需要评估用户在您的网站上执行的后续操作,或者在创建评估之前令牌已过期,则必须再次调用 execute() 以生成新的令牌。

创建评估

请通过向 reCAPTCHA Enterprise API 发送请求或使用 reCAPTCHA Enterprise 客户端库来创建评估。我们建议您根据已设置 reCAPTCHA Enterprise 的位置来选择创建评估的方式。

选择创建评估的方式

您可用于创建评估的方式取决于您的环境:

环境 创建评估的方式
Google Cloud App Engine 或 GKE reCAPTCHA Enterprise 客户端库
Google Cloud Compute Engine

以下任意一个:

  • reCAPTCHA Enterprise REST API(使用 gcloud 工具进行身份验证)
  • reCAPTCHA Enterprise 客户端库
支持服务帐号的第三方云或本地环境

以下任意一个:

  • reCAPTCHA Enterprise REST API(使用 gcloud 工具进行身份验证)
  • reCAPTCHA Enterprise 客户端库
不支持服务帐号的第三方云或本地环境 reCAPTCHA Enterprise REST API(使用 API 密钥进行身份验证)
使用额外的 reCAPTCHA Enterprise 功能(例如多重身份验证 (MFA))的迁移环境

以下任意一个:

  • reCAPTCHA Enterprise REST API(使用 gcloud 工具进行身份验证)
  • reCAPTCHA Enterprise REST API(使用 API 密钥进行身份验证)

使用 REST API 或客户端库创建评估

选择创建评估的适当方法后,请执行以下步骤以创建评估。

REST API

向 reCAPTCHA Enterprise API 发送请求以创建评估。您可以使用 gcloud 工具或 API 密钥进行身份验证。

使用 gcloud 工具进行身份验证

使用 projects.assessments.create 方法创建评估。将此请求发送至 v1 API 端点。

在使用下面的请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • TOKEN:从 grecaptcha.enterprise.execute() 调用返回的令牌
  • KEY:与网站/应用关联的 reCAPTCHA 密钥
  • USER_ACTION(仅适用于基于得分的网站密钥集成):您在 grecaptcha.enterprise.execute() 调用中为 action 指定的用户发起的操作,例如 login。如需了解详情,请参阅操作

HTTP 方法和网址:

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

请求 JSON 正文:

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

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

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

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$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

您应该收到类似以下内容的 JSON 响应:

{
  "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"
}

使用 API 密钥进行身份验证

使用 projects.assessments.create 方法创建评估。将此请求发送至 v1beta1 API 端点。

在使用下面的请求数据之前,请先进行以下替换:

  • API_KEY:与当前项目关联的 API 密钥
  • PROJECT_ID:您的 Google Cloud 项目 ID
  • TOKEN:从 grecaptcha.enterprise.execute() 调用返回的令牌
  • KEY:与网站/应用关联的 reCAPTCHA 密钥
  • USER_ACTION(仅适用于基于得分的网站密钥集成):您在 grecaptcha.enterprise.execute() 调用中为 action 指定的用户发起的操作,例如 login。如需了解详情,请参阅操作

HTTP 方法和网址:

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

请求 JSON 正文:

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

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

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

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$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

您应该收到类似以下内容的 JSON 响应:

{
  "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 = "user_response_token";
            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
                    },
                },
                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 := "user_response_token"
  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,
  }

  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 = "user_response_token";
          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)
                          .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 = "user_response_token";
    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
    });

    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', 'user_response_token');
 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);

 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 = "user_response_token"
  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

  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 = "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

后续步骤

  • 解读评估,并根据得分对您的网站采取适当的措施。