[英]How to set Google Recaptcha Enterprise verification Using Api Key In Java Language?
我无法连接到
发布 url: https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments?key=API_KEY
JSON 身体:
{“事件”:{“令牌”:“令牌”,“siteKey”:“KEY”,“expectedAction”:“USER_ACTION”}}
使用我的代码,我不断收到 ECONNRESET 错误。 当我直接与 postman 建立上述连接时,我能够连接,但是当我尝试在代码中使用 postForObject 时,它拒绝并抛出错误。 我什至尝试使用文档中提供的 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));
}
}
}
这里它要求我设置环境变量GOOGLE_APPLICATION_CREDENTIALS
,但因为我想使用 apiKey。 我应该只能使用 apiKey 进行连接,而无需提及凭据。 任何人都可以帮助我如何使用 apiKey 设置验证,我们将不胜感激。
我在尝试通过集成 ReCaptcha Enterprise 解决我自己的问题时遇到了这篇文章。
来自谷歌:
注意:如果您在不支持服务帐户的第三方云或本地设置 reCAPTCHA Enterprise,则无法使用 reCAPTCHA Enterprise Client Libraries 创建评估
因此,Google API 似乎不支持使用 API 密钥。 在尝试使用 Google API 类时对反序列化有些失望之后,我只是创建了自己的等效类,它们实现了 Serializable 接口并包含与 Google API 等效项相同的字段(例如,MyAssessment 等效于 Google API 评估类)。
您可以尝试类似以下的操作:
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();
}
希望这可以帮助!
这对我有用:
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: https://cloud.google.com/docs/authentication/api-keys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.