### Install the client library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Instructions for installing the reCAPTCHA Enterprise client library for different programming languages.
```APIDOC
## Install the client library
This section provides installation commands for various languages.
### C++
See Setting up a C++ development environment for details.
```
Install-Package Google.Cloud.RecaptchaEnterprise.V1 -Pre
```
### C#
For more information, see Setting Up a C# Development Environment.
```
go get cloud.google.com/go/recaptchaenterprise/v2/apiv1
```
### Java (Maven)
If you are using Maven, add the following to your `pom.xml` file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.
```xml
com.google.cloud
libraries-bom
26.78.0
pom
import
com.google.cloud
google-cloud-recaptchaenterprise
```
### Java (Gradle)
If you are using Gradle, add the following to your dependencies:
```groovy
implementation 'com.google.cloud:google-cloud-recaptchaenterprise:3.84.0'
```
### Java (sbt)
If you are using sbt, add the following to your dependencies:
```scala
libraryDependencies += "com.google.cloud" % "google-cloud-recaptchaenterprise" % "3.84.0"
```
### IDE Plugins
If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:
* Cloud Code for VS Code
* Cloud Code for IntelliJ
The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.
### Node.js
For more information, see Setting Up a Node.js Development Environment.
```bash
npm install @google-cloud/recaptcha-enterprise
```
### PHP
For more information, see Using PHP on Google Cloud.
```bash
composer require google/cloud-recaptcha-enterprise
```
### Python
For more information, see Setting Up a Python Development Environment.
```bash
pip install --upgrade google-cloud-recaptcha-enterprise
```
### Ruby
For more information, see Setting Up a Ruby Development Environment.
```bash
gem install google-cloud-recaptcha_enterprise
```
```
--------------------------------
### PowerShell Request Example
Source: https://docs.cloud.google.com/recaptcha/docs/sms-fraud-detection
Example of how to annotate an assessment using PowerShell.
```APIDOC
$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/ASSESSMENT_ID:annotate" | Select-Object -Expand Content
```
--------------------------------
### PowerShell Request Example
Source: https://docs.cloud.google.com/recaptcha/docs/implement-tokens
Example of how to send a POST request to create a reCAPTCHA Enterprise key using PowerShell.
```APIDOC
## PowerShell Request to Create reCAPTCHA Key
### Description
This example demonstrates how to create a reCAPTCHA Enterprise key using PowerShell. It assumes the request body is saved in a file named `request.json`.
### Command
```powershell
$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/keys" | Select-Object -Expand Content
```
### Notes
- Replace `PROJECT_ID` with your actual Google Cloud project ID.
- Ensure you have authenticated with `gcloud` CLI.
- The `request.json` file should contain the JSON payload for the key creation.
```
--------------------------------
### Install reCAPTCHA Go Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs the reCAPTCHA Enterprise client library for Go. This command fetches the necessary package to integrate reCAPTCHA Enterprise features into Go applications.
```go
go get cloud.google.com/go/recaptchaenterprise/v2/apiv1
```
--------------------------------
### Frontend Integration - Install reCAPTCHA on your website
Source: https://docs.cloud.google.com/recaptcha/docs/fraud-prevention
This section explains how to install a score-based reCAPTCHA key on your website's payment flow and generate a token.
```APIDOC
## Frontend Integration - Install reCAPTCHA on your website
### Description
This endpoint demonstrates how to integrate a score-based reCAPTCHA key on a credit card transaction event. It includes JavaScript to execute the reCAPTCHA challenge and a form to submit the generated token along with payment details.
### Method
Not Applicable (Client-side JavaScript and HTML)
### Endpoint
Not Applicable (Client-side JavaScript and HTML)
### Parameters
None (Client-side)
### Request Example
```html
```
### Response
None (Client-side submission)
### Code Examples
#### JavaScript for executing reCAPTCHA:
```javascript
function submitForm() {
grecaptcha.enterprise.ready(function() {
grecaptcha.enterprise.execute(
'reCAPTCHA_site_key', {action: 'purchase'}).then(function(token) {
document.getElementById("token").value = token;
document.getElementByID("paymentForm").submit();
});
});
}
```
#### HTML for including reCAPTCHA script:
```html
```
#### Full HTML Example:
```html
Protected Payment
```
```
--------------------------------
### cURL Request Example
Source: https://docs.cloud.google.com/recaptcha/docs/implement-tokens
Example of how to send a POST request to create a reCAPTCHA Enterprise key using `curl`.
```APIDOC
## cURL Request to Create reCAPTCHA Key
### Description
This example demonstrates how to create a reCAPTCHA Enterprise key using the `curl` command. It assumes the request body is saved in a file named `request.json`.
### Command
```bash
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/keys"
```
### Notes
- Replace `PROJECT_ID` with your actual Google Cloud project ID.
- Ensure you have authenticated with `gcloud` CLI.
- The `request.json` file should contain the JSON payload for the key creation, as shown in the API reference.
```
--------------------------------
### Example 2: Multiple Widgets Explicit Rendering
Source: https://docs.cloud.google.com/recaptcha/docs/instrument-web-pages-with-checkbox
An HTML example demonstrating the explicit rendering of multiple reCAPTCHA widgets on the same page, each with potentially different configurations and callbacks.
```APIDOC
## Example 2: Multiple Widgets Explicit Rendering
### Description
This example illustrates how to render multiple reCAPTCHA widgets on a single page. Each widget is rendered independently using `grecaptcha.enterprise.render` within the `onloadCallback`, allowing for different configurations (e.g., themes, callbacks) for each widget.
### Method
HTML and JavaScript
### Endpoint
N/A (Client-side rendering)
### Parameters
See previous sections for `grecaptcha.enterprise.render` and script loading parameters. Note the use of `widgetId1`, `widgetId2` to manage individual widget instances.
### Request Example
```html
reCAPTCHA demo: Explicit render for multiple widgets
```
### Response
#### Success Response (200)
Displays three distinct reCAPTCHA widgets. Interactions with each form demonstrate the usage of `getResponse` and `reset` methods using their respective widget IDs.
```
--------------------------------
### Install reCAPTCHA Ruby Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs the reCAPTCHA Enterprise client library for Ruby using the gem command. This is the standard way to add the library to your Ruby projects.
```bash
gem install google-cloud_recaptcha_enterprise
```
--------------------------------
### Example 1: Single Widget Explicit Rendering
Source: https://docs.cloud.google.com/recaptcha/docs/instrument-web-pages-with-checkbox
A complete HTML example demonstrating how to explicitly render a single reCAPTCHA widget after an `onload` callback function is executed.
```APIDOC
## Example 1: Single Widget Explicit Rendering
### Description
This example shows a full HTML page structure where the reCAPTCHA widget is explicitly rendered within a `div` element with the ID `html_element` after the `onloadCallback` function is invoked.
### Method
HTML and JavaScript
### Endpoint
N/A (Client-side rendering)
### Parameters
See previous sections for `grecaptcha.enterprise.render` and script loading parameters.
### Request Example
```html
reCAPTCHA demo: Explicit render after an onload callback
```
### Response
#### Success Response (200)
Displays the reCAPTCHA widget within the specified `div`. Upon form submission, the `g-recaptcha-response` will be sent to the server.
```
--------------------------------
### Migrating to fetchClient
Source: https://docs.cloud.google.com/recaptcha/docs/instrument-ios-apps
This section provides code examples for migrating from the `getClient` method to the `fetchClient` method in Swift and Objective-C.
```APIDOC
## Migrating from getClient to fetchClient
This guide demonstrates how to transition from the `Recaptcha.getClient` method to the more resilient `Recaptcha.fetchClient` method for initializing the reCAPTCHA client.
### Swift with Async/Await
**Old Method (`getClient`)**
```swift
func initializeWithGetClient() {
Task {
do {
self.recaptchaClient = try await Recaptcha.getClient(withSiteKey: "KEY_ID")
} catch let error as RecaptchaError {
print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
}
}
}
```
**New Method (`fetchClient`)**
```swift
func initializeWithFetchClient() {
Task {
do {
self.recaptchaClient = try await Recaptcha.fetchClient(withSiteKey: "KEY_ID")
} catch let error as RecaptchaError {
print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
}
}
}
```
### Swift with Trailing Closures (for OS versions < 13)
**Old Method (`getClient`)**
```swift
func initializeWithGetClient() {
Recaptcha.getClient(withSiteKey: "KEY_ID") { client, error in
guard let client = client else {
print("RecaptchaClient creation error: \(error).")
return
}
self.recaptchaClient = client
}
}
```
**New Method (`fetchClient`)**
```swift
func initializeWithFetchClient() {
Recaptcha.fetchClient(withSiteKey: "KEY_ID") { client, error in
guard let client = client else {
print("RecaptchaClient creation error: \(error).")
return
}
self.recaptchaClient = client
}
}
```
### Objective-C
**Old Method (`getClient`)**
```objectivec
@implementation ViewController
[Recaptcha getClientWithSiteKey:@"KEY_ID"
completion:^void(RecaptchaClient* recaptchaClient, NSError* error) {
if (!recaptchaClient) {
NSLog(@"%@", (RecaptchaError *)error.errorMessage);
return;
}
self->_recaptchaClient = recaptchaClient;
}
];
@end
```
**New Method (`fetchClient`)**
```objectivec
@implementation ViewController
[Recaptcha fetchClientWithSiteKey:@"KEY_ID"
completion:^void(RecaptchaClient* recaptchaClient, NSError* error) {
if (!recaptchaClient) {
NSLog(@"%@", (RecaptchaError *)error.errorMessage);
return;
}
self->_recaptchaClient = recaptchaClient;
}
];
@end
```
**Note:** The `fetchClient` method is designed to automatically retry initialization if network access is not available when the client is created. It will successfully initialize once a network connection is established.
```
--------------------------------
### Install reCAPTCHA PHP Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs the reCAPTCHA Enterprise client library for PHP using Composer. This command adds the Google Cloud reCAPTCHA Enterprise package to your PHP project.
```bash
composer require google/cloud-recaptcha-enterprise
```
--------------------------------
### Install reCAPTCHA C# Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs the reCAPTCHA Enterprise client library for C# using the NuGet package manager. This is a prerequisite for using the reCAPTCHA Enterprise API in C# applications.
```csharp
Install-Package Google.Cloud.RecaptchaEnterprise.V1 -Pre
```
--------------------------------
### Install reCAPTCHA Node.js Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs the reCAPTCHA Enterprise client library for Node.js using npm. This command is used in Node.js projects to add the necessary package for reCAPTCHA integration.
```bash
npm install @google-cloud/recaptcha-enterprise
```
--------------------------------
### Docker Container Setup and Execution
Source: https://docs.cloud.google.com/recaptcha/docs/check-passwords
Instructions on how to build and run the Docker container for the reCAPTCHA Enterprise Password Leak Detection service.
```APIDOC
## Docker Container Setup and Execution
### Description
This section details the steps required to set up and run the Docker container that serves the reCAPTCHA Enterprise Password Leak Detection API.
### Steps
1. **Clone the repository:**
```bash
git clone https://github.com/GoogleCloudPlatform/reCAPTCHA-PLD
cd reCAPTCHA-PLD
```
2. **Build the container:**
```bash
docker build . -t pld-local
```
3. **Start the container:**
Ensure you replace `PROJECT_ID` with your Google Cloud Project ID and `API_KEY` with your reCAPTCHA Enterprise API key. The container uses environment variables for configuration.
```bash
docker run --network host \
-e RECAPTCHA_PROJECT_ID=PROJECT_ID \
-e GOOGLE_CLOUD_API_KEY=API_KEY \
pld-local
```
The container will start and listen for requests on `http://localhost:8080`.
```
--------------------------------
### List Firewall Policies (HTTP Request)
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.firewallpolicies/list?hl=zh-cn
Demonstrates the HTTP GET request to list all firewall policies for a given project. This method requires authentication and specific IAM permissions.
```HTTP
GET https://recaptchaenterprise.googleapis.com/v1/{parent=projects/*}/firewallpolicies
```
--------------------------------
### REST Requests from Command Line
Source: https://docs.cloud.google.com/recaptcha/docs/authentication
Demonstrates how to make REST requests to Google Cloud APIs using gcloud CLI credentials. Includes examples for listing service accounts.
```APIDOC
## REST Requests from the Command Line
### Description
This section explains how to authenticate REST requests made from the command line by leveraging your gcloud CLI credentials. It provides examples using `curl` and PowerShell.
### Authentication Method
Include `gcloud auth print-access-token` in your command to obtain a bearer token for authentication.
### Example: List Service Accounts
This example shows how to list service accounts for a specified project.
**Before you begin:** Replace `PROJECT_ID` with your actual Google Cloud project ID.
#### curl (Linux, macOS, or Cloud Shell)
```bash
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts"
```
#### PowerShell (Windows)
```powershell
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest \
-Method GET \
-Headers $headers \
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts" | Select-Object -Expand Content
```
### Further Information
- For more details on REST and gRPC authentication, see [Authenticate for using REST](https://cloud.google.com/docs/authentication/authenticate-rest).
- To understand the difference between local ADC and gcloud CLI credentials, refer to [gcloud CLI authentication configuration](https://cloud.google.com/sdk/docs/authorizing) and [ADC configuration](https://cloud.google.com/docs/authentication/provide-credentials-adc).
```
--------------------------------
### reCAPTCHA Enterprise API Response Example
Source: https://docs.cloud.google.com/recaptcha/docs/implement-tokens
Example JSON response received after successfully creating a reCAPTCHA Enterprise key. Contains details such as the key's name, display name, and configuration settings.
```json
{
"name": "projects/project-id/keys/7Ldqgs0UBBBBBIn4k7YxEB-LwEh5S9-Gv6QQIWB8m",
"displayName": "DISPLAY_NAME",
"webSettings": {
"allowAllDomains": true,
"allowedDomains": [
"localhost"
],
"integrationType": "SCORE",
},
"wafSettings": {
"wafService": "CA",
"wafFeature": "ACTION_TOKEN"
}
}
```
--------------------------------
### GET /v1/{name=projects/*/keys/*}
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.keys/get?hl=ja
Returns the specified reCAPTCHA Enterprise key.
```APIDOC
## GET projects.keys.get
### Description
Returns the specified key.
### Method
GET
### Endpoint
`https://recaptchaenterprise.googleapis.com/v1/{name=projects/*/keys/*}`
### Path Parameters
- **name** (string) - Required - The name of the requested key, in the format `projects/{project}/keys/{key}`.
### Request Body
The request body must be empty.
### Response
#### Success Response (200)
- **Key** (object) - If successful, the response body contains an instance of `Key`.
### Authorization Scopes
- `https://www.googleapis.com/auth/cloud-platform`
### IAM Permissions
- `recaptchaenterprise.keys.get` on the `name` resource.
```
--------------------------------
### GET /recaptcha/client/initialize
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/Recaptcha
Initializes the reCAPTCHA client for a specific application using the provided site key and a completion handler for the result.
```APIDOC
## GET /recaptcha/client/initialize
### Description
Initializes the reCAPTCHA client instance required for verifying user interactions.
### Method
GET
### Endpoint
/recaptcha/client/initialize
### Parameters
#### Query Parameters
- **siteKey** (string) - Required - The unique reCAPTCHA Site Key assigned to your application.
- **completionHandler** (function) - Required - A callback function that returns the initialized RecaptchaClient object or an error if initialization fails.
### Request Example
{
"siteKey": "your-site-key-here",
"completionHandler": "callback_function"
}
### Response
#### Success Response (200)
- **client** (object) - The initialized RecaptchaClient instance.
#### Response Example
{
"status": "success",
"client": "RecaptchaClientInstance"
}
```
--------------------------------
### GET /recaptcha/initialize
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/Recaptcha?hl=de
Initializes the reCAPTCHA client instance using the provided site key and a completion handler for asynchronous processing.
```APIDOC
## GET /recaptcha/initialize
### Description
Initializes the reCAPTCHA client to enable bot detection and security verification for the application.
### Method
GET
### Endpoint
/recaptcha/initialize
### Parameters
#### Query Parameters
- **siteKey** (string) - Required - The unique reCAPTCHA Site Key assigned to your application.
- **completionHandler** (function) - Required - A callback function that returns the initialized RecaptchaClient instance or an error object upon completion.
### Request Example
{
"siteKey": "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_mxjiZKhX",
"completionHandler": "handleClientInitialization"
}
### Response
#### Success Response (200)
- **status** (string) - Indicates successful initialization.
- **client** (object) - The initialized RecaptchaClient instance.
#### Response Example
{
"status": "success",
"client": "[RecaptchaClientInstance]"
}
```
--------------------------------
### reCAPTCHA Enterprise Client Libraries
Source: https://docs.cloud.google.com/recaptcha/docs/apis
Get started with the reCAPTCHA Enterprise API in your language of choice.
```APIDOC
## Client Libraries
### Description
Get started with the reCAPTCHA Enterprise API in your language of choice.
### Supported Languages
- Java
- Python
- Node.js
- Go
- PHP
- Ruby
- C#
### Usage
Refer to the specific client library documentation for installation and usage instructions.
```
--------------------------------
### Create Compute Engine Instance with Service Account
Source: https://docs.cloud.google.com/recaptcha/docs/authentication
Creates a Compute Engine virtual machine instance and attaches a specified service account to it for authentication. Ensure the service account has the necessary permissions.
```bash
gcloud compute instances create INSTANCE_NAME --zone=ZONE --service-account=SERVICE_ACCOUNT_EMAIL
```
--------------------------------
### Get and Interpret Account Defender Assessment - Java
Source: https://docs.cloud.google.com/recaptcha/docs/account-defender-mobile
This Java code snippet demonstrates how to retrieve the Account Defender assessment from a reCAPTCHA Enterprise response and extract the list of labels. It explains that an empty label list means Account Defender had no additional information to add to the score. It also provides examples of common labels and a link to further documentation on interpreting the assessment.
```Java
response.getAccountDefenderAssessment();
System.out.println(accountDefenderAssessment);
// Get Account Defender label.
List defenderResult =
response.getAccountDefenderAssessment().getLabelsList();
// Based on the result, can you choose next steps.
// If the 'defenderResult' field is empty, it indicates that Account Defender did not have
// anything to add to the score.
// Few result labels: ACCOUNT_DEFENDER_LABEL_UNSPECIFIED, PROFILE_MATCH,
// SUSPICIOUS_LOGIN_ACTIVITY, SUSPICIOUS_ACCOUNT_CREATION, RELATED_ACCOUNTS_NUMBER_HIGH.
// For more information on interpreting the assessment, see:
// https://cloud.google.com/recaptcha-enterprise/docs/account-defender#interpret-assessment-details
System.out.println("Account Defender Assessment Result: " + defenderResult);
}
}
```
--------------------------------
### GET /v1/{name=projects/*/firewallpolicies/*}
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.firewallpolicies/get?hl=es-419
Retrieves a specific firewall policy by its name.
```APIDOC
## GET projects.firewallpolicies.get
### Description
Returns the specified firewall policy.
### Method
GET
### Endpoint
`https://recaptchaenterprise.googleapis.com/v1/{name=projects/*/firewallpolicies/*}`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name of the requested policy, in the format `projects/{project}/firewallpolicies/{firewallpolicy}`.
### Request Body
The request body must be empty.
### Response
#### Success Response (200)
- **FirewallPolicy** (object) - If successful, the response body contains an instance of `FirewallPolicy`.
### Authorization scopes
Requires the following OAuth scope:
- `https://www.googleapis.com/auth/cloud-platform`
### IAM Permissions
Requires the following IAM permission on the `name` resource:
- `recaptchaenterprise.firewallpolicies.get`
```
--------------------------------
### Set up authentication
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Instructions for setting up authentication for Google Cloud APIs using Application Default Credentials (ADC).
```APIDOC
## Set up authentication
To authenticate calls to Google Cloud APIs, client libraries support Application Default Credentials (ADC); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.
### Production Environments
For production environments, the way you set up ADC depends on the service and context. For more information, see Set up Application Default Credentials.
### Local Development Environment
For a local development environment, you can set up ADC with the credentials that are associated with your Google Account:
1. **Install the Google Cloud CLI.** After installation, initialize the Google Cloud CLI by running the following command:
```bash
gcloud init
```
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
2. **Create local authentication credentials.** If you're using a local shell, then create local authentication credentials for your user account:
```bash
gcloud auth application-default login
```
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.
```
--------------------------------
### Sending Requests with cURL and PowerShell
Source: https://docs.cloud.google.com/recaptcha/docs/check-passwords
Examples of how to send POST requests to the running Docker container using cURL and PowerShell.
```APIDOC
## Sending Requests with cURL and PowerShell
### Description
This section provides examples for sending requests to the `POST /createAssessment/` endpoint using both cURL and PowerShell.
### Prerequisites
- The Docker container must be running.
- Save the request body in a file named `request.json`.
### cURL Example
```bash
curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"http://localhost:8080/createAssessment/"
```
### PowerShell Example
```powershell
$headers = @{
"Content-Type" = "application/json; charset=utf-8"
}
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-InFile request.json `
-Uri "http://localhost:8080/createAssessment/" | Select-Object -Expand Content
```
**Note:** Replace `LEAKED_USERNAME` and `LEAKED_PASSWORD` in your `request.json` file with the actual credentials you want to check.
```
--------------------------------
### Setting up Application Default Credentials (ADC)
Source: https://docs.cloud.google.com/recaptcha/docs/authentication
Instructions to set up Application Default Credentials (ADC) for local development environments. This involves installing and initializing the Google Cloud CLI and logging in with your user account.
```APIDOC
## Setting up Application Default Credentials (ADC)
### Description
This section guides you through setting up Application Default Credentials (ADC) in your local environment to authenticate with Google Cloud services. This is crucial for client libraries and other tools.
### Steps
1. **Install Google Cloud CLI:** If you haven't already, install the Google Cloud CLI.
2. **Initialize gcloud CLI:** Run the following command to initialize the gcloud CLI:
```
gcloud init
```
3. **Federated Identity (if applicable):** If you use an external identity provider (IdP), sign in to the gcloud CLI with your federated identity first.
4. **Create Local Credentials:** For local shells, create local authentication credentials for your user account:
```
gcloud auth application-default login
```
*Note: You do not need to perform this step if you are using Cloud Shell.*
### Authentication Error Handling
If you encounter an authentication error and are using an external IdP, ensure you have signed in to the gcloud CLI with your federated identity.
### Credential Storage
Upon successful sign-in, your credentials will be stored in the local credential file used by ADC.
```
--------------------------------
### gcloud CLI Commands for Key Creation
Source: https://docs.cloud.google.com/recaptcha/docs/implement-tokens
Examples of using the `gcloud` command-line tool to create a reCAPTCHA Enterprise web key on Linux, macOS, Cloud Shell, and Windows.
```APIDOC
## gcloud recaptcha keys create
### Description
Use the `gcloud` CLI to create a reCAPTCHA Enterprise web key. The command syntax varies slightly depending on the operating system's shell.
### Linux, macOS, or Cloud Shell
```bash
gcloud recaptcha keys create \
--web \
--display-name=DISPLAY_NAME \
--integration-type=INTEGRATION_TYPE \
--domains=DOMAIN_NAME \
--waf-feature=WAF_FEATURE \
--waf-service=WAF_SERVICE
```
### Windows (PowerShell)
```powershell
gcloud recaptcha keys create `
--web `
--display-name=DISPLAY_NAME `
--integration-type=INTEGRATION_TYPE `
--domains=DOMAIN_NAME `
--waf-feature=WAF_FEATURE `
--waf-service=WAF_SERVICE
```
### Windows (cmd.exe)
```cmd
gcloud recaptcha keys create ^
--web ^
--display-name=DISPLAY_NAME ^
--integration-type=INTEGRATION_TYPE ^
--domains=DOMAIN_NAME ^
--waf-feature=WAF_FEATURE ^
--waf-service=WAF_SERVICE
```
### Parameters
- **--web**: Specifies that the key is for a web integration.
- **--display-name** (string) - Required - A user-friendly name for the key (e.g., a site name).
- **--integration-type** (string) - Required - The type of integration. For web, use `score`.
- **--domains** (string) - Optional - A comma-separated list of domains or subdomains allowed to use the key. Use `--allow-all-domains` to disable domain verification (use with caution).
- **--waf-feature** (string) - Optional - The WAF feature. Use `session-token` for session token integration.
- **--waf-service** (string) - Optional - The WAF service provider. Use `CA` for Cloud Armor.
- **--default-score-threshold** (number) - Optional - For policy-based keys, the universal challenge threshold (preview).
- **--action-score-thresholds** (string) - Optional - For policy-based keys, specifies actions and their score thresholds (preview). Example: `login='{"scoreThreshold": "0.3"}',signup='{"scoreThreshold": "0.1"}'`.
### Notes
- Ensure you are logged into the `gcloud` CLI (`gcloud init` or `gcloud auth login`).
- Replace placeholder values (e.g., `DISPLAY_NAME`, `DOMAIN_NAME`) with your actual information.
```
--------------------------------
### Initialize reCAPTCHA Client (Swift/Objective-C)
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/Recaptcha?hl=de
Demonstrates how to initialize a reCAPTCHA client using a site key. This method supports asynchronous operations and provides a completion handler for results or errors. The SDK supports only one site key per app; attempting to use a different one will result in an exception.
```Swift
class func fetchClient(withSiteKey siteKey: String) async throws -> RecaptchaClient
```
```Objective-C
+ (void)fetchClientWithSiteKey:(nonnull NSString *)siteKey
completion:(nonnull void (^)(RecaptchaClient *_Nullable,
NSError *_Nullable))completion;
```
--------------------------------
### -init Method
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/RecaptchaToken.html?hl=fr
Information regarding the unavailable and undocumented -init method for RecaptchaToken.
```APIDOC
## -init Method
### Description
Unavailable
Undocumented
### Declaration
#### Objective-C
```objectivec
- (instancetype)init NS_UNAVAILABLE;
```
```
--------------------------------
### GET /projects/{project}/firewallpolicies
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rpc/google.cloud.recaptchaenterprise.v1
Lists all firewall policies associated with a specific project.
```APIDOC
## GET /projects/{project}/firewallpolicies
### Description
Retrieves a list of firewall policies belonging to a specific project.
### Method
GET
### Endpoint
/projects/{project}/firewallpolicies
### Parameters
#### Path Parameters
- **project** (string) - Required - The project ID in the format projects/{project}.
#### Query Parameters
- **page_size** (int32) - Optional - The maximum number of policies to return. Default is 10, max is 1000.
- **page_token** (string) - Optional - The next_page_token value returned from a previous request.
### Response
#### Success Response (200)
- **firewall_policies** (array) - List of FirewallPolicy objects.
- **next_page_token** (string) - Token to retrieve the next page of results.
```
--------------------------------
### GET /projects/{project}/keys/{key}
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.keys?hl=it
Retrieves the configuration details for a specific reCAPTCHA Enterprise key.
```APIDOC
## GET projects/{project}/keys/{key}
### Description
Retrieves the details of a specific reCAPTCHA Enterprise key identified by its resource name.
### Method
GET
### Endpoint
projects/{project}/keys/{key}
### Parameters
#### Path Parameters
- **project** (string) - Required - The Google Cloud project ID.
- **key** (string) - Required - The unique identifier for the key.
### Response
#### Success Response (200)
- **name** (string) - The resource name for the Key.
- **displayName** (string) - Human-readable display name.
- **createTime** (string) - The timestamp of key creation.
- **platform_settings** (object) - Platform-specific settings (webSettings, androidSettings, iosSettings, or expressSettings).
#### Response Example
{
"name": "projects/my-project/keys/12345",
"displayName": "My Web Key",
"createTime": "2023-01-01T00:00:00Z"
}
```
--------------------------------
### GET /v1/projects/{project}/firewallpolicies/{firewallpolicy}
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.firewallpolicies/get?hl=ja
Retrieves a specific firewall policy by its name. This endpoint allows you to get the details of an existing firewall policy configuration.
```APIDOC
## GET /v1/projects/{project}/firewallpolicies/{firewallpolicy}
### Description
Returns the specified firewall policy.
### Method
GET
### Endpoint
`https://recaptchaenterprise.googleapis.com/v1/{name=projects/*/firewallpolicies/*}`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name of the requested policy, in the format `projects/{project}/firewallpolicies/{firewallpolicy}`.
### Request Body
The request body must be empty.
### Response
#### Success Response (200)
- **FirewallPolicy** (object) - If successful, the response body contains an instance of `FirewallPolicy`.
#### Response Example
```json
{
"name": "projects/example-project/firewallpolicies/example-policy",
"description": "Example firewall policy",
"rules": [
{
"description": "Block traffic from specific IP range",
"action": "BLOCK",
"conditions": [
{
"field": "ip_range",
"operator": "IN",
"value": "192.168.1.0/24"
}
]
}
],
"updateTime": "2023-10-27T10:00:00Z"
}
```
### Authorization scopes
Requires the following OAuth scope:
- `https://www.googleapis.com/auth/cloud-platform`
### IAM Permissions
Requires the following IAM permission on the `name` resource:
- `recaptchaenterprise.firewallpolicies.get`
```
--------------------------------
### Initialize Google Cloud CLI
Source: https://docs.cloud.google.com/recaptcha/docs/authentication
Initializes the Google Cloud CLI for interacting with Google Cloud services. This is a prerequisite for many subsequent commands.
```bash
gcloud init
```
--------------------------------
### Initialize reCAPTCHA Client (Swift)
Source: https://docs.cloud.google.com/recaptcha/docs/instrument-ios-apps
This snippet shows how to initialize the reCAPTCHA client in Swift for iOS. It includes examples for iOS 13+ and versions below 13, using both async/await and trailing closures.
```APIDOC
## Initialize reCAPTCHA Client (Swift)
### Description
Initializes the reCAPTCHA client with your provided site key. Supports modern Swift with async/await and older versions using trailing closures.
### Method
N/A (Initialization code)
### Endpoint
N/A
### Parameters
None
### Request Example
```swift
// For iOS 13+
import RecaptchaEnterprise
class ViewController: UIViewController {
var recaptchaClient: RecaptchaClient?
override func viewDidLoad() {
super.viewDidLoad() // Ensure super.viewDidLoad() is called
Task {
do {
self.recaptchaClient = try await Recaptcha.fetchClient(withSiteKey: "KEY_ID")
} catch let error as RecaptchaError {
print("RecaptchaClient creation error: \(String(describing: error.errorMessage)).")
}
}
}
}
```
```swift
// For OS versions less than 13
import RecaptchaEnterprise
class ViewController: UIViewController {
var recaptchaClient: RecaptchaClient?
override func viewDidLoad() {
super.viewDidLoad() // Ensure super.viewDidLoad() is called
Recaptcha.fetchClient(withSiteKey: "KEY_ID") { client, error in
guard let client = client else {
print("RecaptchaClient creation error: \(String(describing: error)).")
return
}
self.recaptchaClient = client
}
}
}
```
### Response
N/A (Initialization)
### Response Example
N/A
```
--------------------------------
### Install reCAPTCHA Python Client Library
Source: https://docs.cloud.google.com/recaptcha/docs/libraries
Installs or upgrades the reCAPTCHA Enterprise client library for Python using pip. This command ensures you have the latest version for your Python applications.
```bash
pip install --upgrade google-cloud-recaptcha-enterprise
```
--------------------------------
### Initialize Recaptcha Client with Site Key (Swift)
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/Recaptcha?hl=ja
Initializes a new reCAPTCHA client using a provided site key. This method is suitable for basic client creation and relies on default timeout settings. It may throw an exception if a different site key is used after initialization.
```swift
class func fetchClient(withSiteKey siteKey: String) async throws -> RecaptchaClient
```
--------------------------------
### fetchClientWithSiteKey
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/Recaptcha?hl=zh-cn
Initializes a new reCAPTCHA client for the specified site key.
```APIDOC
## +fetchClientWithSiteKey:completion:
### Description
Builds a new reCAPTCHA Client for the given Site Key. The SDK supports one Site Key; passing a different one will throw an exception.
### Method
Class Method
### Parameters
#### Path Parameters
- **siteKey** (String) - Required - reCAPTCHA Site Key for the app.
- **completion** (Callback) - Required - Callback function to return the RecaptchaClient or an error.
### Request Example
[Recaptcha fetchClientWithSiteKey:@"your-site-key" completion:^(RecaptchaClient *client, NSError *error) { ... }];
### Response
#### Success Response (200)
- **RecaptchaClient** (Object) - The initialized reCAPTCHA client instance.
```
--------------------------------
### Example reCAPTCHA Key Response
Source: https://docs.cloud.google.com/recaptcha/docs/express-standalone
An example JSON response received after successfully creating a Google reCAPTCHA express key. It includes the unique name of the key, its display name, and express settings.
```json
{
"name": "projects/project-id/keys/7Ldqgs0UBBBBBIn4k7YxEB-LwEh5S9-Gv6QQIWB8m",
"displayName": "DISPLAY_NAME,
"expressSettings": {
}
}
```
--------------------------------
### Migrate getClient to fetchClient in Kotlin and Java
Source: https://docs.cloud.google.com/recaptcha/docs/instrument-android-apps
Demonstrates the migration from the `getClient` method to the `fetchClient` method for initializing the reCAPTCHA client. `fetchClient` provides improved network resilience by retrying initialization on network failures.
```kotlin
private fun initializeWithGetClient() {
recaptchaScope.launch {
Recaptcha.getClient(application, "KEY_ID")
.onSuccess { client ->
recaptchaClient = client
}
.onFailure { exception ->
// Handle errors ...
}
}
}
// Migrate to fetchClient
private fun initializeWithFetchClient() {
recaptchaScope.launch {
try {
recaptchaClient = Recaptcha.fetchClient(application, "KEY_ID")
} catch(e: RecaptchaException){
// Handle errors ...
}
}
}
```
```java
// Migrate from getTasksClient
private void initializeWithGetTasksClient() {
Recaptcha
.getTasksClient(getApplication(), "KEY_ID")
.addOnSuccessListener(
this,
new OnSuccessListener() {
@Override
public void onSuccess(RecaptchaTasksClient client) {
recaptchaTasksClient = client;
}
})
.addOnFailureListener(
this,
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Handle errors ...
}
});
}
// Migrate to fetchTaskClient
private void initializeWithFetchTaskClient() {
Recaptcha
.fetchTaskClient(getApplication(), "KEY_ID")
.addOnSuccessListener(
this,
new OnSuccessListener() {
@Override
public void onSuccess(RecaptchaTasksClient client) {
recaptchaTasksClient = client;
}
})
.addOnFailureListener(
this,
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Handle errors ...
}
});
}
```
--------------------------------
### GET /v1/{name=projects/*/firewallpolicies/*}
Source: https://docs.cloud.google.com/recaptcha/docs/reference/rest/v1/projects.firewallpolicies/get?hl=ko
Retrieves the details of a specific firewall policy identified by its name.
```APIDOC
## GET /v1/{name=projects/*/firewallpolicies/*}
### Description
Returns the specified firewall policy resource.
### Method
GET
### Endpoint
https://recaptchaenterprise.googleapis.com/v1/{name=projects/*/firewallpolicies/*}
### Parameters
#### Path Parameters
- **name** (string) - Required - The name of the requested policy, in the format projects/{project}/firewallpolicies/{firewallpolicy}.
### Request Body
The request body must be empty.
### Response
#### Success Response (200)
- **FirewallPolicy** (object) - The instance of the requested firewall policy.
#### Authorization
Requires the following OAuth scope: https://www.googleapis.com/auth/cloud-platform
#### IAM Permissions
Requires the following IAM permission: recaptchaenterprise.firewallpolicies.get
```
--------------------------------
### reCAPTCHA Initialization with Custom Action
Source: https://docs.cloud.google.com/recaptcha/docs/reference/ios/client/api/Classes/RecaptchaAction.html?hl=zh-cn
Demonstrates how to initialize the reCAPTCHA client with a custom action string and an optional dictionary of extra parameters.
```APIDOC
## reCAPTCHA Initialization
### Description
Initializes the reCAPTCHA client with a custom action and optional extra parameters.
### Method
Constructor
### Endpoint
N/A (Client-side initialization)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
// Swift Example
let recaptcha = Recaptcha(customAction: "user_login", extraParameters: ["user_id": "12345"])
```
```objectivec
// Objective-C Example
Recaptcha *recaptcha = [[Recaptcha alloc] initWithCustomAction:@"user_login" extraParameters:@{@"user_id": @"12345"}];
```
### Response
#### Success Response (200)
N/A (Initialization does not return a response)
#### Response Example
None
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.