Cuando el usuario final activa una acción HTML, reCAPTCHA Enterprise envía una respuesta encriptada, llamada token de respuesta (token) del usuario, al navegador del usuario final. Para cualquier tipo de integración de clave de sitio (casilla de verificación o puntuación), debes crear una evaluación mediante el envío del token generado al extremo de evaluación. reCAPTCHA Enterprise procesa el token enviado y, luego, informa su token y su validez.
En este documento, se explica cómo recuperar el token y crear una evaluación. El primer millón de evaluaciones mensuales de reCAPTCHA Enterprise es gratuita. Puedes crear 1 millón de evaluaciones por mes sin habilitar la facturación para tu proyecto de Google Cloud.
Antes de comenzar
Elige el mejor método para configurar reCAPTCHA Enterprise en tu entorno y completa la configuración.
Recupera el token de respuesta del usuario
Recupera el token de respuesta del usuario de las páginas web de una de las siguientes maneras:
- El valor resuelto de la promesa mostrada por la llamada a
grecaptcha.enterprise.execute()
. g-recaptcha-response
parámetro POST cuando el usuario envía el formulario en tu sitio.- Como argumento de string para tu función de devolución de llamada si
data-callback
se especifica en el atributo de etiqueta HTMLg-recaptcha
, o el parámetro de devolución de llamada en el métodogrecaptcha.enterprise.render
.
Para recuperar el token de respuesta del usuario desde aplicaciones para dispositivos móviles, consulta cómo integrar reCAPTCHA Enterprise con apps para iOS o cómo integrar reCAPTCHA Enterprise con apps para Android.
Puedes acceder a cada token de respuesta de reCAPTCHA de usuario una vez.
Si necesitas evaluar una acción posterior que un usuario realiza en tu sitio, o si un token vence antes de que se cree una evaluación, debes volver a llamar a execute()
para generar un token nuevo.
Crea una evaluación
Para crear una evaluación, envía una solicitud a la API de reCAPTCHA Enterprise o usa las bibliotecas cliente de reCAPTCHA Enterprise. Te recomendamos que elijas el método para crear una evaluación según el lugar en el que hayas configurado reCAPTCHA Enterprise.
Elige cómo crear una evaluación
Los métodos que puede utilizar para crear una evaluación dependen de su entorno. En la siguiente tabla, se enumeran los entornos compatibles y sus métodos de evaluación correspondientes:
Entorno | Métodos para crear una evaluación |
---|---|
Google Cloud App Engine o GKE | Bibliotecas cliente de reCAPTCHA Enterprise |
Google Cloud Compute Engine | Cualquiera de las siguientes opciones:
|
Nubes o infraestructuras locales de terceros que admiten cuentas de servicio | Cualquiera de las siguientes opciones:
|
Terceros en la nube o locales que no admiten cuentas de servicio | API de REST de reCAPTCHA Enterprise, que usa claves de API para la autenticación |
Se migró el entorno con funciones adicionales de reCAPTCHA Enterprise, como la autenticación de varios factores (MFA). | Cualquiera de las siguientes opciones:
|
Crea una evaluación mediante la API de REST o las bibliotecas cliente
Después de seleccionar el método adecuado para crear una evaluación, realiza los siguientes pasos. La forma de crear una evaluación es la misma para las claves de sitios basadas en puntuaciones y las de casilla de verificación.
API de REST
Envía una solicitud a la API de reCAPTCHA Enterprise para crear una evaluación. Puedes usar la CLI de gcloud o la clave de API para la autenticación.
Autentica con la CLI de gcloud
Crea una evaluación con el método projects.assessments.create
. Envía esta solicitud al extremo de la API de v1
.
Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:
- PROJECT_ID: El ID del proyecto de Google Cloud.
- TOKEN: Token que se muestra a partir de la llamada
grecaptcha.enterprise.execute()
- KEY: Es la clave de reCAPTCHA asociada con el sitio o la app. Para obtener más información, consulta las claves de reCAPTCHA.
- USER_ACTION (solo para integraciones de clave de sitio basadas en puntuaciones): La acción iniciada por el usuario que especificaste para
action
en la llamadagrecaptcha.enterprise.execute()
, comologin
. Para obtener más información, consulta Acciones.
Método HTTP y URL:
POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments
Cuerpo JSON de la solicitud:
{ "event": { "token": "TOKEN", "siteKey": "KEY", "expectedAction": "USER_ACTION" } }
Para enviar tu solicitud, elige una de estas opciones:
curl
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
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
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
$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
Deberías recibir una respuesta JSON similar a la que se muestra a continuación:
{ "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" }
Recomendamos usar cualquier analizador de JSON en el modo de análisis no estricto para evitar interrupciones si se presentan campos adicionales a la respuesta JSON.
Autentica con una clave de API
Crea una evaluación con el método projects.assessments.create
.
Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:
- API_KEY: La clave de API asociada con el proyecto actual
- PROJECT_ID: El ID del proyecto de Google Cloud.
- TOKEN: Token que se muestra a partir de la llamada
grecaptcha.enterprise.execute()
- KEY: Es la clave de reCAPTCHA asociada con el sitio o la app. Para obtener más información, consulta las claves de reCAPTCHA.
- USER_ACTION (solo para integraciones de clave de sitio basadas en puntuaciones): La acción iniciada por el usuario que especificaste para
action
en la llamadagrecaptcha.enterprise.execute()
, comologin
. Para obtener más información, consulta Acciones.
Método HTTP y URL:
POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY
Cuerpo JSON de la solicitud:
{ "event": { "token": "TOKEN", "siteKey": "KEY", "expectedAction": "USER_ACTION" } }For more information, see reCAPTCHA keys.
Para enviar tu solicitud, elige una de estas opciones:
curl
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
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
Guarda el cuerpo de la solicitud en un archivo llamado request.json
y ejecuta el siguiente comando:
$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
Deberías recibir una respuesta JSON similar a la que se muestra a continuación:
{ "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" }
Recomendamos usar cualquier analizador de JSON en el modo de análisis no estricto para evitar interrupciones en caso de que se introduzcan campos adicionales en la respuesta de 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 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")
{
// 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 = recaptchaSiteKey,
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 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"
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.
*/
func createAssessment(projectID string, recaptchaSiteKey string, token string, recaptchaAction string) {
// Create the recaptcha 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.
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,
}
// 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
Node.js
const {RecaptchaEnterpriseServiceClient} =
require('@google-cloud/recaptcha-enterprise');
/**
* Create an assessment to analyze the risk of an UI action. Note that
* this example does set error boundaries and returns `null` for
* exceptions.
*
* 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.
*/
async function createAssessment({
projectID = "your-project-id",
recaptchaSiteKey = "your-recaptcha-site-key",
token = "action-token",
recaptchaAction = "action-name",
}) {
// Create the reCAPTCHA client & set the project path. There are multiple
// ways to authenticate your client. For more information see:
// https://cloud.google.com/docs/authentication
// 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.
const client = new RecaptchaEnterpriseServiceClient();
const projectPath = client.projectPath(projectID);
// Build the assessment request.
const request = ({
assessment: {
event: {
token: token,
siteKey: recaptchaSiteKey,
},
},
parent: projectPath,
});
// client.createAssessment() can return a Promise or take a Callback
const [ response ] = await client.createAssessment(request);
// Check if the token is valid.
if (!response.tokenProperties.valid) {
console.log("The CreateAssessment call failed because the token was: " +
response.tokenProperties.invalidReason);
return null;
}
// Check if the expected action was executed.
// The `action` property is set by user client in the
// grecaptcha.enterprise.execute() method.
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);
response.riskAnalysis.reasons.forEach((reason) => {
console.log(reason);
});
return response.riskAnalysis.score;
} else {
console.log("The action attribute in your reCAPTCHA tag " +
"does not match the action you are expecting to score");
return null;
}
}
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 {
// 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.
$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
Ruby
¿Qué sigue?
- Interpreta una evaluación y toma una medida adecuada para tu sitio en función de la puntuación.