首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Java语言中的Api键设置Google企业验证?

如何使用Java语言中的Api键设置Google企业验证?
EN

Stack Overflow用户
提问于 2022-05-05 06:33:20
回答 2查看 776关注 0票数 0

我无法连接到

POST网址:https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY

JSON身体:

{“事件”:{“令牌”:“令牌”,"siteKey":“键”,"expectedAction":"USER_ACTION“}}

使用我的代码,我一直得到ECONNRESET错误。当我与邮递员直接命中上述连接时,我能够连接,但当我试图在代码中使用postForObject时,它会拒绝并抛出错误。我甚至尝试使用文档中提供的create Java评估进行连接:

代码语言:javascript
复制
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));
    }
  }
}

这里,它要求我设置环境变量GOOGLE_APPLICATION_CREDENTIALS,但因为我想使用apiKey。我应该能够只使用apiKey进行连接,而不提凭据。任何人能帮助我如何设置使用apiKey的验证,任何帮助将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2022-05-14 00:40:01

我是在尝试通过集成ReCaptcha企业来解决自己的问题时遇到这篇文章的。

来自谷歌:

注意:如果您在第三方云或不支持服务帐户的场所内设置reCAPTCHA企业,则无法使用reCAPTCHA企业客户端库创建评估

因此,似乎Google不支持使用API密钥。在尝试使用Google类时对反序列化有些失望之后,我只创建了自己的等效类,这些类实现了可序列化接口,并包含与Google等效的相同字段(例如。MyAssessment相当于Google评估类)。

您可以尝试类似于以下内容:

代码语言:javascript
复制
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();
}

希望这能有所帮助!

票数 2
EN

Stack Overflow用户

发布于 2022-11-27 23:03:37

这是为我工作的:

代码语言:javascript
复制
        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 key:https://cloud.google.com/docs/authentication/api-keys

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72122850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档