En esta página se explica cómo crear una evaluación para que tu backend pueda verificar la autenticidad del token que envía reCAPTCHA. reCAPTCHA envía una respuesta cifrada, el token de respuesta de reCAPTCHA (también conocido como token), cuando el usuario final activa una acción HTML.
Para cualquier tipo de integración de clave de reCAPTCHA (casilla o puntuación), debes crear una evaluación para analizar los resultados de execute()
en tu backend. Para ello, envía el token generado al endpoint de evaluación.
reCAPTCHA procesa el token enviado e informa de su validez y puntuación.
Las primeras 10.000 evaluaciones mensuales de reCAPTCHA son gratuitas. Para seguir creando evaluaciones después de alcanzar el límite de uso mensual gratuito (10.000 evaluaciones al mes), debes habilitar la facturación en tu Google Cloud proyecto. Para obtener más información sobre la facturación de reCAPTCHA, consulta Información sobre la facturación.
Antes de empezar
- Prepara tu entorno para reCAPTCHA.
- Asegúrate de que tienes el siguiente rol de gestión de identidades y accesos:
Agente de reCAPTCHA Enterprise (
roles/recaptchaenterprise.agent
). - Instala claves basadas en una puntuación, claves de casilla o claves de verificación basadas en políticas en tu sitio web.
-
Configura la autenticación en reCAPTCHA.
El método de autenticación que elijas dependerá del entorno en el que se configure reCAPTCHA. La siguiente tabla te ayudará a elegir el método de autenticación adecuado y la interfaz compatible para configurar la autenticación:
Entorno Interfaz Método de autenticación Google Cloud - REST
- Bibliotecas de cliente
Usa cuentas de servicio asociadas. On-premise u otro proveedor de servicios en la nube REST Usa claves de API o la federación de identidades de cargas de trabajo. Si quieres usar claves de API, te recomendamos que las protejas aplicando restricciones a las claves de API.
Bibliotecas de cliente Utiliza lo siguiente:
- En Python o Java, usa claves de API o la federación de identidades de cargas de trabajo.
Si quieres usar claves de API, te recomendamos que las protejas aplicando restricciones a las claves de API.
- En otros idiomas, usa Federación de identidades de cargas de trabajo.
Recuperar un token
Obtén un token de las páginas web de una de las siguientes formas:
- El valor resuelto de la promesa devuelta por la llamada a
grecaptcha.enterprise.execute()
. - Usa el parámetro POST
g-recaptcha-response
cuando un usuario envíe un formulario en tu sitio. - Como un argumento de cadena para tu función de retrollamada si se especifica
data-callback
en el atributo de la etiqueta HTMLg-recaptcha
o en el parámetro de retrollamada del métodogrecaptcha.enterprise.render
.
Solo puedes acceder al token de cada usuario una vez.
Si necesitas evaluar una acción posterior que realice un usuario en tu sitio o si un token caduca antes de que se cree una evaluación, debes llamar a execute()
de nuevo para generar un token nuevo.
Crear una evaluación
Después de configurar la autenticación, crea una evaluación enviando una solicitud a la API de reCAPTCHA Enterprise o usando las bibliotecas de cliente de reCAPTCHA.
Para mejorar la detección, le recomendamos que transmita los siguientes valores adicionales al crear evaluaciones:
userAgent
: el user-agent se incluye en la solicitud HTTP en el encabezado de la solicitud. Para obtener más información, consulta Información sobre el encabezado de solicitudUser-Agent
en la documentación de Mozilla Developer Network.userIpAddress
: la dirección IP del usuario que envía una solicitud a tu backend está disponible en la solicitud HTTP. Si usas un servidor proxy, la dirección IP está disponible en el encabezado de solicitudX-Forwarded-For
. Para obtener más información sobre cómo obtener la dirección IP, consultaX-Forwarded-For
.ja4
: JA4 es un método de código abierto para crear huellas digitales de clientes TLS. Para obtener más información sobre cómo crear una huella digital JA4, consulta la documentación de JA4 en GitHub.ja3
: JA3 es un método de código abierto para crear huellas digitales de clientes TLS. Para obtener más información sobre cómo crear una huella digital JA3, consulta la documentación de JA3 en GitHub.
Esto ayuda a proteger tu sitio web y tus aplicaciones móviles frente a patrones de ataque avanzados y abusos dirigidos por personas.
La forma de crear una evaluación es la misma para las claves basadas en puntuación, las claves de casilla de verificación y las claves de desafío basadas en políticas (vista previa).
API REST
Crea una evaluación enviando una solicitud a la API de reCAPTCHA. Puedes usar la CLI de gcloud o la clave de API para la autenticación.
Usar la CLI gcloud
Crea una evaluación con el método projects.assessments.create
. Envía esta solicitud al endpoint de la API v1
.
Antes de usar los datos de la solicitud, haz las siguientes sustituciones:
- PROJECT_ID: tu ID de proyecto Google Cloud
- TOKEN: token devuelto de la llamada
grecaptcha.enterprise.execute()
- KEY_ID: la clave de reCAPTCHA asociada al sitio o a la aplicación. Para obtener más información, consulta Claves de reCAPTCHA.
- USER_AGENT: el user-agent de la solicitud del dispositivo del usuario.
- USER_IP_ADDRESS: la dirección IP de la solicitud del dispositivo del usuario.
- JA4: huella digital JA4 del cliente TLS. Te recomendamos que uses
FoxIO-LLC/ja4
para calcular la huella digital de JA4. - JA3: huella digital JA3 del cliente TLS. Te recomendamos que uses
salesforce/ja3
para calcular la huella digital JA3. - USER_ACTION: la acción iniciada por el usuario que has especificado para
action
en la llamadagrecaptcha.enterprise.execute()
, comologin
.Para obtener más información, consulta Nombres de 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_ID", "userAgent": "USER_AGENT", "userIpAddress": "USER_IP_ADDRESS", "ja4": "JA4", "ja3": "JA3", "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 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 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 siguiente:
{ "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", "ja4": "JA4", "ja3": "JA3", "expectedAction": "USER_ACTION" }, "name": "projects/PROJECT_NUMBER/assessments/b6ac310000000000" }
Te recomendamos que uses cualquier analizador JSON en el modo de análisis no estricto para evitar interrupciones si se introducen campos adicionales en la respuesta JSON.
Usar una clave de API
Crea una evaluación con el método projects.assessments.create
. Envía esta solicitud al endpoint de la API v1
.
Antes de usar los datos de la solicitud, haz las siguientes sustituciones:
- API_KEY: clave de API asociada al proyecto actual
- PROJECT_ID: tu ID de proyecto Google Cloud
- TOKEN: token devuelto de la llamada
grecaptcha.enterprise.execute()
- KEY_ID: la clave de reCAPTCHA asociada al sitio o a la aplicación. Para obtener más información, consulta Claves de reCAPTCHA.
- USER_AGENT: el user-agent de la solicitud del dispositivo del usuario.
- USER_IP_ADDRESS: la dirección IP de la solicitud del dispositivo del usuario.
- JA3: huella digital JA3 del cliente SSL. Te recomendamos que uses salesforce/ja3 para calcular JA3.
- USER_ACTION: la acción iniciada por el usuario que has especificado para
action
en la llamadagrecaptcha.enterprise.execute()
, comologin
.Para obtener más información, consulta Nombres de 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_ID", "userAgent": "USER_AGENT", "userIpAddress": "USER_IP_ADDRESS", "ja3": "JA3", "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 "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 siguiente:
{ "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" }
Te recomendamos que uses cualquier analizador JSON en el modo de análisis no estricto para evitar interrupciones si se introducen campos adicionales en la respuesta 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 ( "context" "fmt" recaptcha "cloud.google.com/go/recaptchaenterprise/v2/apiv1" recaptchapb "cloud.google.com/go/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb" ) func main() { // TODO(developer): Replace these variables before running the sample. projectID := "project-id" recaptchaKey := "recaptcha-key" token := "action-token" recaptchaAction := "action-name" createAssessment(projectID, recaptchaKey, token, recaptchaAction) } /** * Create an assessment to analyze the risk of a UI action. * * @param projectID: Google Cloud project ID * @param recaptchaKey: reCAPTCHA key obtained by registering a domain or an app to use the services of reCAPTCHA Enterprise. * @param token: The token obtained from the client on passing the recaptchaKey. * @param recaptchaAction: Action name corresponding to the token. */ func createAssessment(projectID string, recaptchaKey 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: recaptchaKey, } 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/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 a UI action. Note that * this example does set error boundaries and returns `null` for * exceptions. * * projectID: Google Cloud project ID * recaptchaKey: reCAPTCHA key obtained by registering a domain or an app to use the services of reCAPTCHA Enterprise. * token: The token obtained from the client on passing the recaptchaKey. * recaptchaAction: Action name corresponding to the token. * userIpAddress: The IP address of the user sending a request to your backend is available in the HTTP request. * userAgent: The user agent is included in the HTTP request in the request header. * ja4: JA4 fingerprint associated with the request. * ja3: JA3 fingerprint associated with the request. */ async function createAssessment({ projectID = "your-project-id", recaptchaKey = "your-recaptcha-key", token = "action-token", recaptchaAction = "action-name", userIpAddress = "user-ip-address", userAgent = "user-agent", ja4 = "ja4" ja3 = "ja3" }) { // 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: recaptchaKey, userIpAddress: userIpAddress, userAgent: userAgent, ja4: ja4, ja3: ja3, }, }, 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/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 // composer require google/cloud-recaptcha-enterprise require 'vendor/autoload.php'; use Google\Cloud\RecaptchaEnterprise\V1\Client\RecaptchaEnterpriseServiceClient; use Google\Cloud\RecaptchaEnterprise\V1\Event; use Google\Cloud\RecaptchaEnterprise\V1\Assessment; use Google\Cloud\RecaptchaEnterprise\V1\CreateAssessmentRequest; 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/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/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); $request = (new CreateAssessmentRequest()) ->setParent($projectName) ->setAssessment($assessment); try { $response = $client->createAssessment($request); // 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_KEY', 'YOUR_USER_RESPONSE_TOKEN', 'YOUR_GOOGLE_CLOUD_PROJECT_ID' ); ?>
Python
Ruby
Siguientes pasos
- Interpreta una evaluación y toma las medidas adecuadas para tu sitio en función de la puntuación.