Google Cloud reCAPTCHA Enterprise API client library

1.31.0 · active · verified Sat Apr 11

The `google-cloud-recaptcha-enterprise` client library provides Python access to the Google Cloud reCAPTCHA Enterprise API. reCAPTCHA Enterprise protects websites and mobile applications from fraudulent activity, spam, and abuse by using advanced risk analysis and machine learning to distinguish between legitimate users and bots. The library is actively maintained as part of the `google-cloud-python` monorepo and is currently at version 1.31.0, with ongoing releases for features and bug fixes across the Google Cloud client libraries.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an assessment using the reCAPTCHA Enterprise client library in Python. An assessment verifies the authenticity and risk score of a reCAPTCHA response token received from your frontend application. Ensure your Google Cloud project has the reCAPTCHA Enterprise API enabled, and you have configured authentication (e.g., Application Default Credentials) and created a reCAPTCHA site key.

import os
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import types

def create_assessment_sample(
    project_id: str,
    site_key: str,
    token: str,
    action: str,
    user_ip: str = None,
    user_agent: str = None,
) -> None:
    """Creates an assessment to analyze the risk of a UI action.

    Args:
        project_id: Your Google Cloud project ID.
        site_key: The reCAPTCHA key associated with the site or app.
        token: The user's response token for which you want to receive a reCAPTCHA score.
        action: The user-initiated action that you specified for action in the grecaptcha.enterprise.execute() call.
        user_ip: (Optional) The IP address of the user sending a request to your backend.
        user_agent: (Optional) The user agent in the request from the user's device.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    event = types.Event()
    event.site_key = site_key
    event.token = token
    event.expected_action = action

    if user_ip:
        event.user_ip_address = user_ip
    if user_agent:
        event.user_agent = user_agent

    assessment = types.Assessment()
    assessment.event = event

    project_name = client.project_path(project_id)

    try:
        response = client.create_assessment(parent=project_name, assessment=assessment)

        # Check if the token is valid.
        if not response.token_properties.valid:
            print(
                "The create_assessment() call failed because the token was invalid with the following reason: "
                f"{response.token_properties.invalid_reason}"
            )
            return

        # Check if the expected action was executed.
        if response.token_properties.action == action:
            # 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
            print(f"The reCAPTCHA score for this token is: {response.risk_analysis.score}")
            for reason in response.risk_analysis.reasons:
                print(f"  Reason: {reason.name}")
        else:
            print(
                "The action attribute in your reCAPTCHA tag does not match the action you are expecting to score." 
                f"Expected: {action}, Actual: {response.token_properties.action}"
            )
    except Exception as e:
        print(f"Error creating assessment: {e}")

# Example Usage (replace with your actual project_id, site_key, and token)
if __name__ == "__main__":
    project_id = os.environ.get('GOOGLE_CLOUD_PROJECT_ID', 'your-project-id')
    # The site key generated for your reCAPTCHA Enterprise site/app
    site_key = os.environ.get('RECAPTCHA_ENTERPRISE_SITE_KEY', 'your-site-key')
    # The token obtained from the client-side reCAPTCHA execution
    token = os.environ.get('RECAPTCHA_ENTERPRISE_TOKEN', 'your-recaptcha-token')
    action = 'login'
    user_ip = '192.0.2.1' # Example IP, use actual user's IP
    user_agent = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.65 Mobile Safari/537.36'

    if project_id == 'your-project-id' or site_key == 'your-site-key' or token == 'your-recaptcha-token':
        print("Please set GOOGLE_CLOUD_PROJECT_ID, RECAPTCHA_ENTERPRISE_SITE_KEY, and RECAPTCHA_ENTERPRISE_TOKEN environment variables or replace placeholders in the script.")
    else:
        create_assessment_sample(project_id, site_key, token, action, user_ip, user_agent)

view raw JSON →