Skip to content

Commit e56a11f

Browse files
authored
docs(samples): create recaptcha samples (#535)
* (feat): init commit client code samples * (feat): init commit * (docs): modified var names * (refactor): modified checking for site key properties * (docs): added region tag and comments * (docs): modified comments and var names * (docs): changed the print var * (refactor): dis-allow amp traffic * (refactor): added assessment name and modified var name. * fix: added copyright. Minor var name fixes. * fix: changed key type. Added copyright. * feat: init commit adding test cases and snippets * refactor: lint fix and added dependencies * refactor: added webdrivermanager to remove driver binary dependency * fix: lint error * docs(samples): init commit client code samples * (feat): init commit * (docs): modified var names * (refactor): modified checking for site key properties * (docs): added region tag and comments * (docs): modified comments and var names * (docs): changed the print var * (refactor): dis-allow amp traffic * (refactor): added assessment name and modified var name. * fix: added copyright. Minor var name fixes. * fix: changed key type. Added copyright. * feat: init commit adding test cases and snippets * refactor: lint fix and added dependencies * refactor: added webdrivermanager to remove driver binary dependency * fix: lint error * fix: pom mismatch fixup * fix: pom mismatch fixup
1 parent 9c6acfe commit e56a11f

File tree

11 files changed

+930
-0
lines changed

11 files changed

+930
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package app;
18+
19+
import org.springframework.boot.SpringApplication;
20+
import org.springframework.boot.autoconfigure.SpringBootApplication;
21+
22+
@SpringBootApplication
23+
public class Main {
24+
25+
public static void main(String[] args) {
26+
SpringApplication.run(Main.class, args);
27+
}
28+
29+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package app;
18+
19+
import org.springframework.stereotype.Controller;
20+
import org.springframework.ui.ModelMap;
21+
import org.springframework.web.bind.annotation.GetMapping;
22+
import org.springframework.web.bind.annotation.RequestMapping;
23+
import org.springframework.web.bind.annotation.RequestParam;
24+
import org.springframework.web.servlet.ModelAndView;
25+
26+
27+
@Controller
28+
@RequestMapping
29+
public class MainController {
30+
31+
@GetMapping(value = "/")
32+
public static ModelAndView landingPage(
33+
@RequestParam("recaptchaSiteKey") String recaptchaSiteKey) {
34+
ModelMap map = new ModelAndView().getModelMap();
35+
map.put("siteKey", recaptchaSiteKey);
36+
return new ModelAndView("index", map);
37+
}
38+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package recaptcha;
18+
19+
// [START recaptcha_enterprise_create_assessment]
20+
21+
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
22+
import com.google.recaptchaenterprise.v1.Assessment;
23+
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
24+
import com.google.recaptchaenterprise.v1.Event;
25+
import com.google.recaptchaenterprise.v1.ProjectName;
26+
import com.google.recaptchaenterprise.v1.RiskAnalysis.ClassificationReason;
27+
import java.io.IOException;
28+
29+
public class CreateAssessment {
30+
31+
public static void main(String[] args) throws IOException {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String projectID = "project-id";
34+
String recaptchaSiteKey = "recaptcha-site-key";
35+
String token = "action-token";
36+
String recaptchaAction = "action-name";
37+
38+
createAssessment(projectID, recaptchaSiteKey, token, recaptchaAction);
39+
}
40+
41+
42+
/**
43+
* Create an assessment to analyze the risk of an UI action.
44+
*
45+
* @param projectID : GCloud Project ID
46+
* @param recaptchaSiteKey : Site key obtained by registering a domain/app to use recaptcha
47+
* services.
48+
* @param token : The token obtained from the client on passing the recaptchaSiteKey.
49+
* @param recaptchaAction : Action name corresponding to the token.
50+
*/
51+
public static void createAssessment(String projectID, String recaptchaSiteKey, String token,
52+
String recaptchaAction)
53+
throws IOException {
54+
// Initialize client that will be used to send requests. This client only needs to be created
55+
// once, and can be reused for multiple requests. After completing all of your requests, call
56+
// the `client.close()` method on the client to safely
57+
// clean up any remaining background resources.
58+
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
59+
60+
// Specify a name for this assessment.
61+
String assessmentName = "assessment-name";
62+
// Set the properties of the event to be tracked.
63+
Event event = Event.newBuilder()
64+
.setSiteKey(recaptchaSiteKey)
65+
.setToken(token)
66+
.build();
67+
68+
// Build the assessment request.
69+
CreateAssessmentRequest createAssessmentRequest = CreateAssessmentRequest.newBuilder()
70+
.setParent(ProjectName.of(projectID).toString())
71+
.setAssessment(Assessment.newBuilder().setEvent(event).setName(assessmentName).build())
72+
.build();
73+
74+
Assessment response = client.createAssessment(createAssessmentRequest);
75+
76+
// Check if the token is valid.
77+
if (!response.getTokenProperties().getValid()) {
78+
System.out.println("The CreateAssessment call failed because the token was: " +
79+
response.getTokenProperties().getInvalidReason().name());
80+
return;
81+
}
82+
83+
// Check if the expected action was executed.
84+
if (!response.getTokenProperties().getAction().equals(recaptchaAction)) {
85+
System.out.println(
86+
"The action attribute in reCAPTCHA tag is: " + response.getTokenProperties()
87+
.getAction());
88+
System.out.println("The action attribute in the reCAPTCHA tag " +
89+
"does not match the action (" + recaptchaAction + ") you are expecting to score");
90+
return;
91+
}
92+
93+
// Get the risk score and the reason(s).
94+
// For more information on interpreting the assessment,
95+
// see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
96+
float recaptchaScore = response.getRiskAnalysis().getScore();
97+
System.out.println("The reCAPTCHA score is: " + recaptchaScore);
98+
99+
for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
100+
System.out.println(reason);
101+
}
102+
}
103+
}
104+
}
105+
// [END recaptcha_enterprise_create_assessment]
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package recaptcha;
18+
19+
// [START recaptcha_enterprise_create_site_key]
20+
21+
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
22+
import com.google.recaptchaenterprise.v1.CreateKeyRequest;
23+
import com.google.recaptchaenterprise.v1.Key;
24+
import com.google.recaptchaenterprise.v1.ProjectName;
25+
import com.google.recaptchaenterprise.v1.WebKeySettings;
26+
import com.google.recaptchaenterprise.v1.WebKeySettings.IntegrationType;
27+
import java.io.IOException;
28+
29+
30+
public class CreateSiteKey {
31+
32+
public static void main(String[] args) throws IOException {
33+
// TODO(developer): Replace these variables before running the sample.
34+
String projectID = "your-project-id";
35+
String domainName = "domain-name";
36+
37+
createSiteKey(projectID, domainName);
38+
}
39+
40+
/**
41+
* Create reCAPTCHA Site key which binds a domain name to a unique key.
42+
*
43+
* @param projectID : GCloud Project ID.
44+
* @param domainName : Specify the domain name in which the reCAPTCHA should be activated.
45+
*/
46+
public static String createSiteKey(String projectID, String domainName) throws IOException {
47+
// Initialize client that will be used to send requests. This client only needs to be created
48+
// once, and can be reused for multiple requests. After completing all of your requests, call
49+
// the `client.close()` method on the client to safely
50+
// clean up any remaining background resources.
51+
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
52+
53+
// Set the type of reCAPTCHA to be displayed.
54+
// For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys
55+
Key scoreKey = Key.newBuilder()
56+
.setDisplayName("any_descriptive_name_for_the_key")
57+
.setWebSettings(WebKeySettings.newBuilder()
58+
.addAllowedDomains(domainName)
59+
.setAllowAmpTraffic(false)
60+
.setIntegrationType(IntegrationType.SCORE).build())
61+
.build();
62+
63+
CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
64+
.setParent(ProjectName.of(projectID).toString())
65+
.setKey(scoreKey)
66+
.build();
67+
68+
// Get the name of the created reCAPTCHA site key.
69+
Key response = client.createKey(createKeyRequest);
70+
String keyName = response.getName();
71+
String recaptchaSiteKey = keyName.substring(keyName.lastIndexOf("/") + 1);
72+
System.out.println("reCAPTCHA Site key created successfully. Site Key: " + recaptchaSiteKey);
73+
return recaptchaSiteKey;
74+
}
75+
}
76+
}
77+
// [END recaptcha_enterprise_create_site_key]
78+
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package recaptcha;
18+
19+
// [START recaptcha_enterprise_delete_site_key]
20+
21+
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
22+
import com.google.recaptchaenterprise.v1.DeleteKeyRequest;
23+
import com.google.recaptchaenterprise.v1.KeyName;
24+
import java.io.IOException;
25+
import java.util.concurrent.ExecutionException;
26+
import java.util.concurrent.TimeUnit;
27+
import java.util.concurrent.TimeoutException;
28+
29+
public class DeleteSiteKey {
30+
31+
public static void main(String[] args)
32+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
33+
// TODO(developer): Replace these variables before running the sample.
34+
String projectID = "your-project-id";
35+
String recaptchaSiteKey = "recaptcha-site-key";
36+
37+
deleteSiteKey(projectID, recaptchaSiteKey);
38+
}
39+
40+
/**
41+
* Delete the given reCAPTCHA site key present under the project ID.
42+
*
43+
* @param projectID: GCloud Project ID.
44+
* @param recaptchaSiteKey: Specify the site key to be deleted.
45+
*/
46+
public static void deleteSiteKey(String projectID, String recaptchaSiteKey)
47+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
48+
// Initialize client that will be used to send requests. This client only needs to be created
49+
// once, and can be reused for multiple requests. After completing all of your requests, call
50+
// the `client.close()` method on the client to safely
51+
// clean up any remaining background resources.
52+
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
53+
54+
// Set the project ID and reCAPTCHA site key.
55+
DeleteKeyRequest deleteKeyRequest = DeleteKeyRequest.newBuilder()
56+
.setName(KeyName.of(projectID, recaptchaSiteKey).toString())
57+
.build();
58+
59+
client.deleteKeyCallable().futureCall(deleteKeyRequest).get(5, TimeUnit.SECONDS);
60+
System.out.println("reCAPTCHA Site key successfully deleted !");
61+
}
62+
}
63+
}
64+
// [END recaptcha_enterprise_delete_site_key]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package recaptcha;
18+
19+
// [START recaptcha_enterprise_get_site_key]
20+
21+
import com.google.api.core.ApiFuture;
22+
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
23+
import com.google.recaptchaenterprise.v1.GetKeyRequest;
24+
import com.google.recaptchaenterprise.v1.Key;
25+
import com.google.recaptchaenterprise.v1.KeyName;
26+
import java.io.IOException;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
29+
import java.util.concurrent.TimeoutException;
30+
31+
public class GetSiteKey {
32+
33+
public static void main(String[] args)
34+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
String projectID = "your-project-id";
37+
String recaptchaSiteKey = "recaptcha-site-key";
38+
39+
getSiteKey(projectID, recaptchaSiteKey);
40+
}
41+
42+
43+
/**
44+
* Get the reCAPTCHA site key present under the project ID.
45+
*
46+
* @param projectID: GCloud Project ID.
47+
* @param recaptchaSiteKey: Specify the site key to get the details.
48+
*/
49+
public static void getSiteKey(String projectID, String recaptchaSiteKey)
50+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
51+
// Initialize client that will be used to send requests. This client only needs to be created
52+
// once, and can be reused for multiple requests. After completing all of your requests, call
53+
// the `client.close()` method on the client to safely
54+
// clean up any remaining background resources.
55+
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
56+
57+
// Construct the "GetSiteKey" request.
58+
GetKeyRequest getKeyRequest = GetKeyRequest.newBuilder()
59+
.setName(KeyName.of(projectID, recaptchaSiteKey).toString())
60+
.build();
61+
62+
// Wait for the operation to complete.
63+
ApiFuture<Key> futureCall = client.getKeyCallable().futureCall(getKeyRequest);
64+
Key key = futureCall.get(5, TimeUnit.SECONDS);
65+
66+
System.out.println("Successfully obtained the key !" + key.getName());
67+
}
68+
}
69+
}
70+
// [END recaptcha_enterprise_get_site_key]

0 commit comments

Comments
 (0)