Websiteschlüssel aktualisieren

Aktualisiert die Eigenschaften des angegebenen Websiteschlüssels für die angegebene Projekt-ID.

Codebeispiel

Java

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei reCAPTCHA Enterprise zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.GetKeyRequest;
import com.google.recaptchaenterprise.v1.Key;
import com.google.recaptchaenterprise.v1.KeyName;
import com.google.recaptchaenterprise.v1.UpdateKeyRequest;
import com.google.recaptchaenterprise.v1.WebKeySettings;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class UpdateSiteKey {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectID = "your-project-id";
    String recaptchaSiteKeyID = "recaptcha-site-key-id";
    String domainName = "domain-name";

    updateSiteKey(projectID, recaptchaSiteKeyID, domainName);
  }

  /**
   * Update the properties of the given site key present under the project id.
   *
   * @param projectID: GCloud Project ID.
   * @param recaptchaSiteKeyID: Specify the site key.
   * @param domainName: Specify the domain name for which the settings should be updated.
   */
  public static void updateSiteKey(String projectID, String recaptchaSiteKeyID, String domainName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `client.close()` method on the client to safely
    // clean up any remaining background resources.
    try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

      // Set the name and the new settings for the key.
      UpdateKeyRequest updateKeyRequest =
          UpdateKeyRequest.newBuilder()
              .setKey(
                  Key.newBuilder()
                      .setDisplayName("any descriptive name for the key")
                      .setName(KeyName.of(projectID, recaptchaSiteKeyID).toString())
                      .setWebSettings(
                          WebKeySettings.newBuilder()
                              .setAllowAmpTraffic(true)
                              .addAllowedDomains(domainName)
                              .build())
                      .build())
              .build();

      client.updateKeyCallable().futureCall(updateKeyRequest).get();

      // Check if the key has been updated.
      GetKeyRequest getKeyRequest =
          GetKeyRequest.newBuilder()
              .setName(KeyName.of(projectID, recaptchaSiteKeyID).toString())
              .build();
      Key response = client.getKey(getKeyRequest);

      // Get the changed property.
      boolean allowedAmpTraffic = response.getWebSettings().getAllowAmpTraffic();
      if (!allowedAmpTraffic) {
        System.out.println(
            "Error! reCAPTCHA Site key property hasn't been updated. Please try again !");
        return;
      }
      System.out.println("reCAPTCHA Site key successfully updated !");
    }
  }
}

PHP

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei reCAPTCHA Enterprise zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\ApiCore\ApiException;
use Google\Cloud\RecaptchaEnterprise\V1\Client\RecaptchaEnterpriseServiceClient;
use Google\Cloud\RecaptchaEnterprise\V1\Key;
use Google\Cloud\RecaptchaEnterprise\V1\UpdateKeyRequest;
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings;
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings\ChallengeSecurityPreference;
use Google\Cloud\RecaptchaEnterprise\V1\WebKeySettings\IntegrationType;
use Google\Protobuf\FieldMask;

/**
 * Update an existing reCAPTCHA site key
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $keyId The 40 char long key ID you wish to update
 * @param string $updatedName The updated display name of the reCAPTCHA key
 */
function update_key(
    string $projectId,
    string $keyId,
    string $updatedName
): void {
    $client = new RecaptchaEnterpriseServiceClient();
    $formattedKeyName = $client->keyName($projectId, $keyId);

    // Create the settings for the key.
    // In order to create other keys we'll use AndroidKeySettings or IOSKeySettings
    $settings = new WebKeySettings();

    // Allow the key to work for all domains(Not recommended)
    // $settings->setAllowAllDomains(false);
    // ...or explicitly set the allowed domains for the key as an array of strings
    $settings->setAllowedDomains(['google.com']);

    // Specify the type of the key
    // - score based key -> IntegrationType::SCORE
    // - checkbox based key -> IntegrationType::CHECKBOX
    // Read https://cloud.google.com/recaptcha-enterprise/docs/choose-key-type
    $settings->setIntegrationType(IntegrationType::CHECKBOX);

    // Specify the possible challenge frequency and difficulty
    // Read https://cloud.google.com/recaptcha-enterprise/docs/reference/rest/v1/projects.keys#challengesecuritypreference
    $settings->setChallengeSecurityPreference(ChallengeSecurityPreference::SECURITY);

    $key = new Key();
    $key->setName($formattedKeyName);
    $key->setDisplayName($updatedName);
    $key->setWebSettings($settings);

    $updateMask = new FieldMask([
        'paths' => ['display_name', 'web_settings']
    ]);

    try {
        $updateKeyRequest = (new UpdateKeyRequest())
            ->setKey($key)
            ->setUpdateMask($updateMask);
        $updatedKey = $client->updateKey($updateKeyRequest);

        printf('The key: %s is updated.' . PHP_EOL, $updatedKey->getDisplayName());
    } catch (ApiException $e) {
        if ($e->getStatus() === 'NOT_FOUND') {
            printf('The key with Key ID: %s doesn\'t exist.' . PHP_EOL, $keyId);
        } else {
            print('updateKey() call failed with the following error: ');
            print($e);
        }
    }
}

Python

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei reCAPTCHA Enterprise zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import time

from google.cloud import recaptchaenterprise_v1

def update_site_key(project_id: str, recaptcha_site_key: str, domain_name: str) -> None:
    """
    Update the properties of the given site key present under the project id.

    Args:
    project_id: GCloud Project ID.
    recaptcha_site_key: Specify the site key.
    domain_name: Specify the domain name for which the settings should be updated.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Construct the key details.
    key_name = f"projects/{project_id}/keys/{recaptcha_site_key}"

    # Set the name and the new settings for the key.
    web_settings = recaptchaenterprise_v1.WebKeySettings()
    web_settings.allow_amp_traffic = True
    web_settings.allowed_domains.append(domain_name)

    key = recaptchaenterprise_v1.Key()
    key.display_name = "any descriptive name for the key"
    key.name = key_name
    key.web_settings = web_settings

    update_key_request = recaptchaenterprise_v1.UpdateKeyRequest()
    update_key_request.key = key
    client.update_key(update_key_request)

    time.sleep(5)

    # Retrieve the key and check if the property is updated.
    get_key_request = recaptchaenterprise_v1.GetKeyRequest()
    get_key_request.name = key_name
    response = client.get_key(get_key_request)
    web_settings = response.web_settings

    # Get the changed property.
    if not web_settings.allow_amp_traffic:
        print(
            "Error! reCAPTCHA Site key property hasn't been updated. Please try again !"
        )
    else:
        print("reCAPTCHA Site key successfully updated ! ")

Ruby

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich bei reCAPTCHA Enterprise zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

require "google/cloud/recaptcha_enterprise"

# Update a site key registered for a domain/app to use recaptcha services.
#
# @param project_id [String] GCloud Project ID.
# @param site_key [String] Site key to be updated.
# @param domain [String] Domain to register for recaptcha services.
# @return [void]
def update_site_key project_id:, site_key:, domain:
  # Create the reCAPTCHA client.
  client = ::Google::Cloud::RecaptchaEnterprise.recaptcha_enterprise_service

  request_key = client.get_key name: "projects/#{project_id}/keys/#{site_key}"
  request_key.web_settings.allowed_domains.push domain
  request_key.web_settings.allow_amp_traffic = true

  client.update_key key: request_key

  # Retrieve the key and check if the property is updated.
  response = client.get_key name: "projects/#{project_id}/keys/#{site_key}"
  web_settings = response.web_settings

  puts "reCAPTCHA Site key successfully updated with allow_amp_traffic to #{web_settings.allow_amp_traffic}!"
end

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.