Skip to content

Commit f136c23

Browse files
committed
docs(api-key-samples): add samples and tests for using api keys
1 parent cd631ea commit f136c23

10 files changed

Lines changed: 797 additions & 0 deletions

‎auth/pom.xml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ limitations under the License.
6767
<artifactId>google-auth-library-oauth2-http</artifactId>
6868
<version>1.8.1</version>
6969
</dependency>
70+
<dependency>
71+
<groupId>com.google.cloud</groupId>
72+
<artifactId>google-cloud-apikeys</artifactId>
73+
<version>0.1.0</version>
74+
</dependency>
7075
<!-- END dependencies -->
7176
<dependency>
7277
<groupId>commons-io</groupId>
@@ -79,6 +84,12 @@ limitations under the License.
7984
<version>4.13.2</version>
8085
<scope>test</scope>
8186
</dependency>
87+
<dependency>
88+
<groupId>com.google.truth</groupId>
89+
<artifactId>truth</artifactId>
90+
<version>1.1.3</version>
91+
<scope>test</scope>
92+
</dependency>
8293
<!-- START dependencies -->
8394
</dependencies>
8495
<!-- END dependencies -->
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright 2022 Google Inc.
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+
// [START auth_cloud_create_api_key]
18+
19+
import com.google.api.apikeys.v2.ApiKeysClient;
20+
import com.google.api.apikeys.v2.ApiTarget;
21+
import com.google.api.apikeys.v2.CreateKeyRequest;
22+
import com.google.api.apikeys.v2.Key;
23+
import com.google.api.apikeys.v2.LocationName;
24+
import com.google.api.apikeys.v2.Restrictions;
25+
import java.io.IOException;
26+
import java.util.concurrent.ExecutionException;
27+
import java.util.concurrent.TimeUnit;
28+
import java.util.concurrent.TimeoutException;
29+
30+
public class CreateApiKey {
31+
32+
public static void main(String[] args)
33+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
34+
// TODO(Developer): Before running this sample,
35+
// 1. Replace the variable(s) below.
36+
// 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
37+
// 3. Make sure you have the necessary permission to create API keys.
38+
String projectId = "GOOGLE_CLOUD_PROJECT_ID";
39+
40+
createApiKey(projectId);
41+
}
42+
43+
// Creates an API key.
44+
public static Key createApiKey(String projectId)
45+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
46+
// Initialize client that will be used to send requests. This client only needs to be created
47+
// once, and can be reused for multiple requests. After completing all of your requests, call
48+
// the `apiKeysClient.close()` method on the client to safely
49+
// clean up any remaining background resources.
50+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
51+
52+
Key key = Key.newBuilder()
53+
.setDisplayName("My first API key")
54+
// Set the API key restriction.
55+
// You can also set browser/ server/ android/ ios based restrictions.
56+
// For more information on API key restriction, see:
57+
// https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
58+
.setRestrictions(Restrictions.newBuilder()
59+
// Restrict the API key usage by specifying the target service and methods.
60+
// The API key can only be used to authenticate the specified methods in the service.
61+
.addApiTargets(ApiTarget.newBuilder()
62+
.setService("translate.googleapis.com")
63+
.addMethods("translate.googleapis.com.TranslateText")
64+
.build())
65+
.build())
66+
.build();
67+
68+
// Initialize request and set arguments.
69+
CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
70+
// API keys can only be global.
71+
.setParent(LocationName.of(projectId, "global").toString())
72+
.setKey(key)
73+
.build();
74+
75+
// Make the request and wait for the operation to complete.
76+
Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);
77+
78+
// For authenticating with the API key, use the value in "result.getKeyString()".
79+
// To restrict the usage of this API key, use the value in "result.getName()".
80+
System.out.printf("Successfully created an API key: %s", result.getName());
81+
return result;
82+
}
83+
}
84+
}
85+
// [END auth_cloud_create_api_key]
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* Copyright 2022 Google Inc.
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+
// [START auth_cloud_delete_api_key]
18+
19+
import com.google.api.apikeys.v2.ApiKeysClient;
20+
import com.google.api.apikeys.v2.DeleteKeyRequest;
21+
import com.google.api.apikeys.v2.Key;
22+
import java.io.IOException;
23+
import java.util.concurrent.ExecutionException;
24+
import java.util.concurrent.TimeUnit;
25+
import java.util.concurrent.TimeoutException;
26+
27+
public class DeleteApiKey {
28+
29+
public static void main(String[] args)
30+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
31+
// TODO(Developer): Before running this sample,
32+
// 1. Replace the variable(s) below.
33+
// 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
34+
// 3. Make sure you have the necessary permission to delete API keys.
35+
// Google Cloud project id that has the API key to delete.
36+
String projectId = "GOOGLE_CLOUD_PROJECT_ID";
37+
// The API key id to delete.
38+
String apiKeyId = "API_KEY_ID";
39+
40+
deleteApiKey(projectId, apiKeyId);
41+
}
42+
43+
// Deletes an API key.
44+
public static void deleteApiKey(String projectId, String apiKeyId)
45+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
46+
// Initialize client that will be used to send requests. This client only needs to be created
47+
// once, and can be reused for multiple requests. After completing all of your requests, call
48+
// the `apiKeysClient.close()` method on the client to safely
49+
// clean up any remaining background resources.
50+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
51+
52+
// Initialize the delete request and set the argument.
53+
DeleteKeyRequest deleteKeyRequest = DeleteKeyRequest.newBuilder()
54+
.setName(String.format("project/%s/locations/global/keys/%s", projectId, apiKeyId))
55+
.build();
56+
57+
// Make the request and wait for the operation to complete.
58+
Key deletedKey = apiKeysClient.deleteKeyAsync(deleteKeyRequest)
59+
.get(3, TimeUnit.MINUTES);
60+
61+
System.out.printf("Successfully deleted the API key: %s", deletedKey.getName());
62+
}
63+
}
64+
}
65+
// [END auth_cloud_delete_api_key]
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Copyright 2022 Google Inc.
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+
// [START auth_cloud_lookup_api_key]
18+
19+
import com.google.api.apikeys.v2.ApiKeysClient;
20+
import com.google.api.apikeys.v2.LookupKeyRequest;
21+
import com.google.api.apikeys.v2.LookupKeyResponse;
22+
import java.io.IOException;
23+
24+
public class LookupApiKey {
25+
26+
public static void main(String[] args) throws IOException {
27+
// TODO(Developer): Before running this sample,
28+
// 1. Replace the variable(s) below.
29+
// 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
30+
// 3. Make sure you have the necessary permission to view API keys.
31+
// API key string to retrieve the API key name.
32+
String apiKeyString = "API_KEY_STRING";
33+
34+
lookupApiKey(apiKeyString);
35+
}
36+
37+
// Retrieves name (full path) of an API key using the API key string.
38+
public static void lookupApiKey(String apiKeyString) throws IOException {
39+
// Initialize client that will be used to send requests. This client only needs to be created
40+
// once, and can be reused for multiple requests. After completing all of your requests, call
41+
// the `apiKeysClient.close()` method on the client to safely
42+
// clean up any remaining background resources.
43+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
44+
45+
// Initialize the lookup request and set the API key string.
46+
LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
47+
.setKeyString(apiKeyString)
48+
.build();
49+
50+
// Make the request and obtain the response.
51+
LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);
52+
53+
System.out.printf("Successfully retrieved the API key name: %s", response.getName());
54+
}
55+
}
56+
}
57+
// [END auth_cloud_lookup_api_key]
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Copyright 2022 Google Inc.
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+
// [START auth_cloud_restrict_api_key_android]
18+
19+
import com.google.api.apikeys.v2.AndroidApplication;
20+
import com.google.api.apikeys.v2.AndroidKeyRestrictions;
21+
import com.google.api.apikeys.v2.ApiKeysClient;
22+
import com.google.api.apikeys.v2.Key;
23+
import com.google.api.apikeys.v2.Restrictions;
24+
import com.google.api.apikeys.v2.UpdateKeyRequest;
25+
import com.google.protobuf.FieldMask;
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 RestrictApiKeyAndroid {
32+
33+
public static void main(String[] args)
34+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
35+
// TODO(Developer): Before running this sample,
36+
// 1. Replace the variable(s) below.
37+
String projectId = "GOOGLE_CLOUD_PROJECT_ID";
38+
39+
// ID of the key to restrict. This ID is auto-created during key creation.
40+
// This is different from the key string. To obtain the key_id,
41+
// you can also use the lookup api: client.lookupKey()
42+
String keyId = "key_id";
43+
44+
restrictApiKeyAndroid(projectId, keyId);
45+
}
46+
47+
// Restricts an API key based on android applications.
48+
// Specifies the Android application that can use the key.
49+
public static Key restrictApiKeyAndroid(String projectId, String keyId)
50+
throws IOException, ExecutionException, InterruptedException, 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 `apiKeysClient.close()` method on the client to safely
54+
// clean up any remaining background resources.
55+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
56+
57+
// Restrict the API key usage by specifying the allowed android applications.
58+
Restrictions restrictions = Restrictions.newBuilder()
59+
.setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
60+
.addAllowedApplications(AndroidApplication.newBuilder()
61+
// Specify the android application's package name and SHA1 fingerprint.
62+
.setPackageName("com.google.appname")
63+
.setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
64+
.build())
65+
.build())
66+
.build();
67+
68+
Key key = Key.newBuilder()
69+
.setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
70+
// Set the restriction(s).
71+
// For more information on API key restriction, see:
72+
// https://cloud.google.com/docs/authentication/api-keys
73+
.setRestrictions(restrictions)
74+
.build();
75+
76+
// Initialize request and set arguments.
77+
UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
78+
.setKey(key)
79+
.setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
80+
.build();
81+
82+
// Make the request and wait for the operation to complete.
83+
Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
84+
85+
// For authenticating with the API key, use the value in "result.getKeyString()".
86+
System.out.printf("Successfully updated the API key: %s", result.getName());
87+
return result;
88+
}
89+
}
90+
}
91+
// [END auth_cloud_restrict_api_key_android]

0 commit comments

Comments
 (0)