为移动应用创建评估

本页面介绍了如何创建评估,以便您的后端验证 reCAPTCHA 发送的令牌的真实性。 当最终用户触发操作时,reCAPTCHA 会发送加密响应,即 reCAPTCHA 响应令牌(简称令牌)。

您必须创建 评估,方法是将生成的令牌提交到 评估端点 ,以便在后端评估 execute() 的结果。reCAPTCHA 会处理 提交的令牌,并报告令牌的有效性和得分。

每月前 10,000 次 reCAPTCHA 评估免费。如果您想在达到每月免费用量限额(每月 10,000 次评估)后继续创建评估,则必须为您的 Google Cloud 项目启用结算功能。如需详细了解 reCAPTCHA 的结算 ,请参阅 结算信息

准备工作

  1. 为 Google Cloud Fraud Defense 准备环境
  2. 确保您具有以下 Identity and Access Management 角色: reCAPTCHA Enterprise 代理 (roles/recaptchaenterprise.agent)。
  3. 在 iOS 应用上安装基于得分的密钥在 Android 应用上
  4. 为 Fraud Defense 设置身份验证。

    您选择的身份验证方法取决于 Fraud Defense 的设置环境。下表可帮助您选择适当的身份验证方法和受支持的接口来设置身份验证:

    环境 接口 身份验证方法
    Google Cloud
    • REST
    • 客户端库
    使用关联的服务账号
    本地或其他云服务提供商 REST 使用 API 密钥工作负载身份联合

    如果您想使用 API 密钥,建议您通过 应用 API 密钥限制来保护 API 密钥。

    客户端库

    使用以下资源:

检索令牌

execute() 调用的响应中检索令牌。

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

创建评估

设置身份验证后,请通过向 reCAPTCHA Enterprise API 发送请求或使用 reCAPTCHA 客户端库来创建评估。

为了提高检测效果,我们建议您在创建评估时传递以下附加值:

  • userAgent:用户代理包含在 HTTP 请求的请求标头中。如需了解详情,请参阅 Mozilla 开发者网络文档中的了解 User-Agent 请求标头
  • userIpAddress:向后端发送请求的用户的 IP 地址可在 HTTP 请求中获取。如果您使用代理服务器,则 IP 地址可在 X-Forwarded-For 请求标头中获取。如需详细了解如何获取 IP 地址,请参阅 X-Forwarded-For
  • ja4:JA4 是一种用于对 TLS 客户端进行指纹识别的开源方法。如需详细了解如何创建 JA4 指纹,请参阅 GitHub 上的 JA4 文档
  • ja3:JA3 是一种用于对 TLS 客户端进行指纹识别的开源方法。如需详细了解如何创建 JA3 指纹,请参阅 GitHub 上的 JA3 文档

这有助于保护您的网站和移动应用免受高级攻击模式和人为滥用的侵害。

REST API

通过向 reCAPTCHA API 发送请求来创建评估。您可以使用 gcloud CLI 或 API 密钥进行身份验证。

使用 gcloud CLI

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

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

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • TOKEN:从 grecaptcha.enterprise.execute() 调用返回的令牌
  • KEY_ID:与网站或应用关联的 reCAPTCHA 密钥。如需了解详情,请参阅 reCAPTCHA 密钥
  • USER_AGENT:来自用户设备的请求中的用户代理。
  • USER_IP_ADDRESS:来自用户设备的请求中的 IP 地址。
  • JA4:TLS 客户端的 JA4 指纹。我们建议使用 FoxIO-LLC/ja4 计算 JA4 指纹。
  • JA3:TLS 客户端的 JA3 指纹。我们建议使用 salesforce/ja3 计算 JA3 指纹。
  • USER_ACTION:您在 grecaptcha.enterprise.execute() 调用中为 action 指定的用户发起的操作,例如 login

    如需了解详情, 请参阅操作名称

HTTP 方法和网址:

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

请求 JSON 正文:

{
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY_ID",
    "userAgent": "USER_AGENT",
    "userIpAddress": "USER_IP_ADDRESS",
    "ja4": "JA4",
    "ja3": "JA3",
    "expectedAction": "USER_ACTION"
  }
}

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

curl

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

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/assessments"

PowerShell

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

$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/assessments" | Select-Object -Expand Content

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

{
  "tokenProperties": {
    "valid": true,
    "com.example.app" or "iosBundleId": "com.example.app",
    "action": "homepage",
    "createTime": "2019-03-28T12:24:17.894Z"
   },
  "riskAnalysis": {
    "score": 0.1,
    "reasons": ["AUTOMATION"]
  },
 "event": {
    "token": "TOKEN",
    "siteKey": "KEY_ID",
    "userAgent": "USER_AGENT",
    "userIpAddress": "USER_IP_ADDRESS",
    "ja4": "JA4",
    "ja3": "JA3",
    "expectedAction": "USER_ACTION"
  },
  "name": "projects/PROJECT_NUMBER/assessments/b6ac310000000000"
}

我们建议您在非严格解析模式下使用任何 JSON 解析器,以防止在 JSON 响应引入任何其他字段时发生任何中断。

使用 API 密钥

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

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

  • API_KEY:与当前项目关联的 API 密钥
  • PROJECT_ID:您的 Google Cloud 项目 ID
  • TOKEN:从 grecaptcha.enterprise.execute() 调用返回的令牌
  • KEY_ID:与网站或应用关联的 reCAPTCHA 密钥。如需了解详情,请参阅 reCAPTCHA 密钥
  • USER_AGENT:来自用户设备的请求中的用户代理。
  • USER_IP_ADDRESS:来自用户设备的请求中的 IP 地址。
  • JA3:SSL 客户端的 JA3 指纹。我们建议使用 salesforce/ja3 计算 JA3 指纹。
  • USER_ACTION:您在 grecaptcha.enterprise.execute() 调用中为 action 指定的用户发起的操作,例如 login

    如需了解详情, 请参阅操作名称

HTTP 方法和网址:

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

请求 JSON 正文:

{
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY_ID",
    "userAgent": "USER_AGENT",
    "userIpAddress": "USER_IP_ADDRESS",
    "ja3": "JA3",
    "expectedAction": "USER_ACTION"
  }
}

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

curl

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

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://recaptchaenterprise.googleapis.com/v1/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/v1/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"
  },
  "riskAnalysis": {
    "score": 0.1,
    "reasons": ["AUTOMATION"]
  },
  "event": {
    "token": "TOKEN",
    "siteKey": "KEY_ID",
    "userAgent": "USER_AGENT",
    "userIpAddress": "USER_IP_ADDRESS",
    "ja3": "JA3",
    "expectedAction": "USER_ACTION"
  },
  "name": "projects/PROJECT_NUMBER/assessments/b6ac310000000000"
}

我们建议您在非严格解析模式下使用任何 JSON 解析器,以防止在 JSON 响应引入任何其他字段时发生任何中断。

C#

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

  public class CreateAssessmentSample
  {
      // Create an assessment to analyze the risk of a UI action.
      // projectID: Google Cloud project ID.
      // recaptchaKey: reCAPTCHA key obtained by registering a domain or an app to use reCAPTCHA Enterprise.
      // token: The token obtained from the client on passing the recaptchaKey.
      // recaptchaAction: Action name corresponding to the token.
      public void createAssessment(string projectID = "project-id", string recaptchaKey = "recaptcha-key",
          string token = "action-token", string recaptchaAction = "action-name")
      {

          // Create the client.
          // TODO: To avoid memory issues, move this client generation outside
          // of this example, and cache it (recommended) or call client.close()
          // before exiting this method.
          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 = recaptchaKey,
                      Token = token,
                      ExpectedAction = recaptchaAction
                  },
              },
              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 reasons.
          // For more information on interpreting the assessment,
          // see: https://cloud.google.com/recaptcha/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 (