简体   繁体   English

如何使用 Api Key In Java Language 设置 Google Recaptcha Enterprise 验证?

[英]How to set Google Recaptcha Enterprise verification Using Api Key In Java Language?

I am not being able to connect to我无法连接到

POST url: https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY发布 url: https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY

JSON BODY: JSON 身体:

{ "event": { "token": "TOKEN", "siteKey": "KEY", "expectedAction": "USER_ACTION" } } {“事件”:{“令牌”:“令牌”,“siteKey”:“KEY”,“expectedAction”:“USER_ACTION”}}

using my code, I keep getting ECONNRESET error.使用我的代码,我不断收到 ECONNRESET 错误。 When I am hitting the above connection directly with postman, I am able to connect but when I am trying to use postForObject in code it refuses and throws error.当我直接与 postman 建立上述连接时,我能够连接,但是当我尝试在代码中使用 postForObject 时,它拒绝并抛出错误。 I have even tried connecting using create assessment for Java provided in documention:我什至尝试使用文档中提供的 Java 创建评估进行连接:

import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.recaptchaenterprise.v1.Assessment;
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
import com.google.recaptchaenterprise.v1.Event;
import com.google.recaptchaenterprise.v1.ProjectName;
import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason;
import java.io.IOException;

public class CreateAssessment {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectID = "project-id";
    String recaptchaSiteKey = "recaptcha-site-key";
    String token = "action-token";
    String recaptchaAction = "action-name";

    createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction);
  }

  /**
   * Create an assessment to analyze the risk of an UI action. Assessment approach is the same for
   * both 'score' and 'checkbox' type recaptcha site keys.
   *
   * @param projectID : GCloud Project ID
   * @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
   *     services. (score/ checkbox type)
   * @param token : The token obtained from the client on passing the recaptchaSiteKey.
   * @param recaptchaAction : Action name corresponding to the token.
   */
  public static void createAssessment(
      String projectID, String recaptchaSiteKey, String token, String recaptchaAction)
      throws IOException {
    // 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 properties of the event to be tracked.
      Event event = Event.newBuilder().setSiteKey(recaptchaSiteKey).setToken(token).build();

      // Build the assessment request.
      CreateAssessmentRequest createAssessmentRequest =
          CreateAssessmentRequest.newBuilder()
              .setParent(ProjectName.of(projectID).toString())
              .setAssessment(Assessment.newBuilder().setEvent(event).build())
              .build();

      Assessment response = client.createAssessment(createAssessmentRequest);

      // Check if the token is valid.
      if (!response.getTokenProperties().getValid()) {
        System.out.println(
            "The CreateAssessment call failed because the token was: "
                + response.getTokenProperties().getInvalidReason().name());
        return;
      }

      // Check if the expected action was executed.
      // (If the key is checkbox type and 'action' attribute wasn't set, skip this check.)
      if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {
        System.out.println(
            "The action attribute in reCAPTCHA tag is: "
                + response.getTokenProperties().getAction());
        System.out.println(
            "The action attribute in the reCAPTCHA tag "
                + "does not match the action ("
                + recaptchaAction
                + ") you are expecting to score");
        return;
      }

      // Get the reason(s) and the risk score.
      // For more information on interpreting the assessment,
      // see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
      for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
        System.out.println(reason);
      }

      float recaptchaScore = response.getRiskAnalysis().getScore();
      System.out.println("The reCAPTCHA score is: " + recaptchaScore);

      // Get the assessment name (id). Use this to annotate the assessment.
      String assessmentName = response.getName();
      System.out.println(
          "Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1));
    }
  }
}

Here it asking me to set environment variable GOOGLE_APPLICATION_CREDENTIALS , but since I want to use apiKey.这里它要求我设置环境变量GOOGLE_APPLICATION_CREDENTIALS ,但因为我想使用 apiKey。 I should be able to connect only using apiKey and not mentioning credentials.我应该只能使用 apiKey 进行连接,而无需提及凭据。 Can anyone help me in how to setup verification using apiKey, any help is appreciated.任何人都可以帮助我如何使用 apiKey 设置验证,我们将不胜感激。

I came across this post while trying to solve my own issues with integrating ReCaptcha Enterprise.我在尝试通过集成 ReCaptcha Enterprise 解决我自己的问题时遇到了这篇文章。

From Google:来自谷歌:

Note: If you set up reCAPTCHA Enterprise on a third-party cloud or on-premises that do not support service accounts, you cannot use the reCAPTCHA Enterprise Client Libraries to create an assessment注意:如果您在不支持服务帐户的第三方云或本地设置 reCAPTCHA Enterprise,则无法使用 reCAPTCHA Enterprise Client Libraries 创建评估

So, it seems the Google APIs do not support using an API key.因此,Google API 似乎不支持使用 API 密钥。 After some frustration with deserialization while trying to use the Google API classes, I simply created my own equivalent classes which implement the Serializable interface and contain the same fields as the Google API equivalents (eg. MyAssessment is equivalent to the Google API Assessment class).在尝试使用 Google API 类时对反序列化有些失望之后,我只是创建了自己的等效类,它们实现了 Serializable 接口并包含与 Google API 等效项相同的字段(例如,MyAssessment 等效于 Google API 评估类)。

You might try something similar to the following:您可以尝试类似以下的操作:

public static void createAssessment(String projectId, String siteKey, String token, String action, String apiKey) {
    String format = "https://recaptchaenterprise.googleapis.com/v1/projects/%s/assessments";
    // Create the URI using the key as a Query parameter
    URI uri = UriComponentsBuilder
        .fromUriString(String.format(format, projectId))
        .queryParam("key", apiKey)
        .build()
        .toUri();
    
    // Build the request
    MyEvent event = new MyEvent(siteKey, token, action);
    MyAssessmentRequest assessmentRequest = new MyAssessmentRequest(event);
    RequestEntity<MyAssessmentRequest> req = RequestEntity.post(uri).body(assessment);

    // Make the call
    ResponseEntity<MyAssessmentResponse> resp = new RestTemplate().exchange(req, MyAssessmentResponse.class);

    // Process the response
    // MyRiskAnalysis ra = response.getBody().getRiskAnalysis();
    // MyTokenProperties tp = response.getBody().getTokenProperties();
    // MyEvent e = response.getBody().getEvent();
}

Hope this helps!希望这可以帮助!

This is working for me:这对我有用:

        final RecaptchaEnterpriseServiceSettings settings = RecaptchaEnterpriseServiceSettings.newBuilder()
            
            .setCredentialsProvider(NoCredentialsProvider.create())
            .setHeaderProvider(FixedHeaderProvider.create("x-goog-api-key", "your api key"))
            .build();
      try (RecaptchaEnterpriseServiceClient client = 
              RecaptchaEnterpriseServiceClient.create(settings)) {...}

x-goog-api-key is mentioned here: https://cloud.google.com/docs/authentication/api-keys这里提到了 x-goog-api-key: https://cloud.google.com/docs/authentication/api-keys

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在google recaptcha中设置本地化 - how to set localization in google recaptcha 如何使用Java Automation API为Enterprise Architect中的枚举条目设置初始值? - How to set an initial value for an enumeration entry in Enterprise Architect using Java Automation API? Google reCaptcha 验证握手异常 - Google reCaptcha verification handshake exception 如何使用 java KMS API 设置密钥环的保护级别? - How to set protection level for key ring using java KMS API? 如何使用HTML或Java在IE 11中设置企业模式 - How to set Enterprise Mode in IE 11 Using HTML or Java 如何使用 Java API 在 Google Dataproc 集群上设置可选属性? - How to set optional properties on Google Dataproc Cluster using Java API? 无法验证 google recaptcha 企业。 收到错误:java.io.IOException:应用程序默认凭据不可用 - Unable to validate google recaptcha enterprise. getting error: java.io.IOException: The Application Default Credentials are not available 如何在 Java 中设置语言? - How to set language in Java? 使用 Java 使用 Twilio API 进行电话验证 - Phone Verification with the Twilio API using java 如何绕过 Google reCAPTCHA 使用 Selenium 进行测试 - How to bypass Google reCAPTCHA for testing using Selenium
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM