Halaman ini menjelaskan cara membuat penilaian agar backend Anda dapat memverifikasi keaslian token yang dikirim reCAPTCHA Enterprise. reCAPTCHA Enterprise mengirim respons terenkripsi, yaitu token respons reCAPTCHA (token), saat pengguna akhir memicu tindakan.
Anda harus membuat penilaian untuk menilai hasil execute()
di backend Anda dengan mengirimkan token yang dibuat ke endpoint penilaian.
reCAPTCHA Enterprise memproses token yang dikirimkan serta melaporkan validitas dan skor token.
1 juta penilaian bulanan reCAPTCHA Enterprise pertama tidak dikenai biaya. Untuk terus membuat penilaian setelah mencapai batas penggunaan bulanan gratis (1 juta penilaian per bulan), Anda harus mengaktifkan penagihan untuk project Google Cloud Anda. Untuk mengetahui informasi selengkapnya tentang penagihan reCAPTCHA Enterprise, lihat Informasi penagihan.
Sebelum memulai
- Menyiapkan lingkungan Anda untuk reCAPTCHA Enterprise.
- Pastikan Anda memiliki peran Identity and Access Management berikut:
Agen reCAPTCHA Enterprise (
roles/recaptchaenterprise.agent
). - Instal kunci berbasis skor di aplikasi iOS atau di aplikasi Android.
-
Siapkan autentikasi ke reCAPTCHA Enterprise.
Metode autentikasi yang Anda pilih bergantung pada lingkungan tempat reCAPTCHA Enterprise disiapkan. Tabel berikut membantu Anda memilih metode autentikasi yang tepat dan antarmuka yang didukung untuk menyiapkan autentikasi:
Lingkungan Antarmuka Metode autentikasi Google Cloud - REST
- Library klien
Gunakan akun layanan terlampir. Lokal atau penyedia cloud lain REST Gunakan kunci API atau federasi identitas workload. Jika Anda ingin menggunakan kunci API, sebaiknya amankan kunci API dengan menerapkan pembatasan kunci API.
Library klien Gunakan resource berikut:
- Untuk Python atau Java, gunakan kunci API atau federasi identitas workload.
Jika Anda ingin menggunakan kunci API, sebaiknya amankan kunci API dengan menerapkan pembatasan kunci API.
- Untuk bahasa lain, gunakan Workload identity federation.
Mengambil token
Ambil token dari respons panggilan execute()
.
Anda hanya dapat mengakses token setiap pengguna satu kali.
Jika Anda perlu menilai tindakan selanjutnya yang dilakukan pengguna di aplikasi seluler Anda, atau jika masa berlaku token habis sebelum penilaian dibuat, Anda harus memanggil execute()
lagi untuk membuat token baru.
Membuat penilaian
Setelah menyiapkan autentikasi, buat penilaian dengan mengirim permintaan ke reCAPTCHA Enterprise API atau dengan menggunakan Library Klien reCAPTCHA Enterprise.
Untuk meningkatkan deteksi, sebaiknya Anda meneruskan nilai tambahan berikut saat membuat penilaian: userAgent
, userIpAddress
, dan ja3
.
REST API
Buat penilaian dengan mengirim permintaan ke reCAPTCHA Enterprise API. Anda dapat menggunakan gcloud CLI atau kunci API untuk autentikasi.
Menggunakan gcloud CLI
Buat penilaian menggunakan metode projects.assessments.create
. Kirim permintaan ini ke endpoint v1
API.
Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:
- PROJECT_ID: project ID Google Cloud Anda
- TOKEN: token yang ditampilkan dari panggilan
grecaptcha.enterprise.execute()
- KEY_ID: kunci reCAPTCHA yang terkait dengan situs atau aplikasi. Untuk informasi selengkapnya, lihat kunci reCAPTCHA.
- USER_AGENT: agen pengguna dalam permintaan dari perangkat pengguna.
- USER_IP_ADDRESS: alamat IP dalam permintaan dari perangkat pengguna.
- JA3: Sidik jari JA3 untuk klien SSL. Sebaiknya gunakan salesforce/ja3 untuk menghitung JA3.
- USER_ACTION: tindakan yang dimulai pengguna yang Anda tentukan untuk
action
dalam panggilangrecaptcha.enterprise.execute()
, sepertilogin
.Untuk informasi selengkapnya, lihat Nama tindakan.
Metode HTTP dan URL:
POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments
Isi JSON permintaan:
{ "event": { "token": "TOKEN", "siteKey": "KEY_ID", "userAgent": "USER_AGENT", "userIpAddress": "USER_IP_ADDRESS", "ja3": "JA3", "expectedAction": "USER_ACTION" } }
Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:
curl
Simpan isi permintaan dalam file bernama request.json
,
dan jalankan perintah berikut:
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
Simpan isi permintaan dalam file bernama request.json
,
dan jalankan perintah berikut:
$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
Anda akan melihat respons JSON seperti berikut:
{ "tokenProperties": { "valid": true, "com.example.app" or "iosBundleId": "com.example.app", "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" }
Sebaiknya gunakan parser JSON dalam mode penguraian yang tidak ketat untuk mencegah gangguan jika ada kolom tambahan yang disertakan ke respons JSON.
Menggunakan kunci API
Buat penilaian menggunakan metode projects.assessments.create
. Kirim permintaan ini ke endpoint v1
API.
Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:
- API_KEY: Kunci API yang terkait dengan project saat ini
- PROJECT_ID: project ID Google Cloud Anda
- TOKEN: token yang ditampilkan dari panggilan
grecaptcha.enterprise.execute()
- KEY_ID: kunci reCAPTCHA yang terkait dengan situs atau aplikasi. Untuk informasi selengkapnya, lihat kunci reCAPTCHA.
- USER_AGENT: agen pengguna dalam permintaan dari perangkat pengguna.
- USER_IP_ADDRESS: alamat IP dalam permintaan dari perangkat pengguna.
- JA3: Sidik jari JA3 untuk klien SSL. Sebaiknya gunakan salesforce/ja3 untuk menghitung JA3.
- USER_ACTION: tindakan yang dimulai pengguna yang Anda tentukan untuk
action
dalam panggilangrecaptcha.enterprise.execute()
, sepertilogin
.Untuk informasi selengkapnya, lihat Nama tindakan.
Metode HTTP dan URL:
POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY
Isi JSON permintaan:
{ "event": { "token": "TOKEN", "siteKey": "KEY_ID", "userAgent": "USER_AGENT", "userIpAddress": "USER_IP_ADDRESS", "ja3": "JA3", "expectedAction": "USER_ACTION" } }
Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:
curl
Simpan isi permintaan dalam file bernama request.json
,
dan jalankan perintah berikut:
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
Simpan isi permintaan dalam file bernama request.json
,
dan jalankan perintah berikut:
$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
Anda akan melihat respons JSON seperti berikut:
{ "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" }
Sebaiknya gunakan parser JSON dalam mode penguraian yang tidak ketat untuk mencegah gangguan jika ada kolom tambahan yang disertakan ke respons 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/apiv1" recaptchapb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" ) 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. */ async function createAssessment({ projectID = "your-project-id", recaptchaKey = "your-recaptcha-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: recaptchaKey, }, }, 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\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/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); 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_KEY', 'YOUR_USER_RESPONSE_TOKEN', 'YOUR_GOOGLE_CLOUD_PROJECT_ID' ); ?>
Python
Ruby
Langkah selanjutnya
- Interpretasikan penilaian dan lakukan tindakan yang sesuai untuk aplikasi seluler Anda berdasarkan skor tersebut.