Skip to content

Commit 51748e8

Browse files
authored
feat: Java SDK Api Key authorization sample (GoogleCloudPlatform#9586)
* feat: create java sample for authorizing in google cloud using api key credentials * formatting fix * code cleanup from linter * code cleanup from linter * code cleanup from unintentional formatting changes * moved test into separate file * added tests * removed unnecessary return * removed extra newline * do not pass in arguments to main + auto create api key for unit tests * add java doc to new class * fixed license header * enclosed key creation in try + delete in finally
1 parent 3144e93 commit 51748e8

File tree

5 files changed

+158
-7
lines changed

5 files changed

+158
-7
lines changed

auth/README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ You can then run a given `ClassName` via:
3535
mvn exec:java -Dexec.mainClass=com.google.cloud.auth.samples.AuthExample
3636
-Dexec.args="compute"
3737

38+
### Analyze text sentiment using LanguageService API with API key authentication
39+
40+
Create an API key via the [Google Cloud console:](https://developers.google.com/workspace/guides/create-credentials#api-key)
41+
42+
Once you have an API key replace it in the main function in ApiKeyAuthExample and run the following command
43+
44+
mvn exec:java -Dexec.mainClass=com.google.cloud.auth.samples.ApiKeyAuthExample
45+
3846
## Downscoping with Credential Access Boundaries
3947

4048
The same configuration above applies.
@@ -44,7 +52,7 @@ you must provide both a bucket name and object name under the TODO(developer): i
4452

4553
You can then run `DownscopingExample` via:
4654

47-
mvn exec:exec
55+
mvn exec:java -Dexec.mainClass=com.google.cloud.auth.samples.DownscopingExample
4856

4957
## Tests
5058
Run all tests:

auth/pom.xml

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ limitations under the License.
4848
<dependency>
4949
<groupId>com.google.cloud</groupId>
5050
<artifactId>libraries-bom</artifactId>
51-
<version>26.32.0</version>
51+
<version>26.49.0</version>
5252
<type>pom</type>
5353
<scope>import</scope>
5454
</dependency>
@@ -72,6 +72,10 @@ limitations under the License.
7272
<groupId>com.google.cloud</groupId>
7373
<artifactId>google-cloud-apikeys</artifactId>
7474
</dependency>
75+
<dependency>
76+
<groupId>com.google.cloud</groupId>
77+
<artifactId>google-cloud-language</artifactId>
78+
</dependency>
7579
<!-- END dependencies -->
7680
<dependency>
7781
<groupId>junit</groupId>
@@ -104,11 +108,6 @@ limitations under the License.
104108
</executions>
105109
<configuration>
106110
<executable>java</executable>
107-
<arguments>
108-
<argument>-classpath</argument>
109-
<classpath />
110-
<argument>com.google.cloud.auth.samples.DownscopingExample</argument>
111-
</arguments>
112111
</configuration>
113112
</plugin>
114113
</plugins>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* Copyright 2024 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 com.google.cloud.auth.samples;
18+
19+
// [START auth_cloud_api_key]
20+
import com.google.cloud.language.v2.AnalyzeSentimentResponse;
21+
import com.google.cloud.language.v2.Document;
22+
import com.google.cloud.language.v2.LanguageServiceClient;
23+
import com.google.cloud.language.v2.LanguageServiceSettings;
24+
import java.io.IOException;
25+
26+
// [END auth_cloud_api_key]
27+
28+
/**
29+
* Demonstrate how to authenticate requests using an API Key using the Language API as an example.
30+
*/
31+
public class ApiKeyAuthExample {
32+
33+
// [START auth_cloud_api_key]
34+
static String authenticateUsingApiKey(String apiKey) throws IOException {
35+
LanguageServiceSettings settings =
36+
LanguageServiceSettings.newBuilder().setApiKey(apiKey).build();
37+
try (LanguageServiceClient client = LanguageServiceClient.create(settings)) {
38+
Document document =
39+
Document.newBuilder()
40+
.setContent("Hello World!")
41+
.setType(Document.Type.PLAIN_TEXT)
42+
.build();
43+
44+
AnalyzeSentimentResponse actualResponse = client.analyzeSentiment(document);
45+
46+
return actualResponse.getDocumentSentiment().toString();
47+
}
48+
}
49+
// [END auth_cloud_api_key]
50+
51+
public static void main(String[] args) throws IOException {
52+
// TODO(Developer): Before running this sample, replace the variable(s) below.
53+
// API key created in developer's project.
54+
String apiKey = "api-key";
55+
56+
authenticateUsingApiKey(apiKey);
57+
}
58+
}

auth/src/test/java/com/google/cloud/auth/samples/AuthExampleIT.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import static org.junit.Assert.assertNotNull;
2020
import static org.junit.Assert.assertTrue;
2121

22+
import com.google.api.apikeys.v2.Key;
23+
import com.google.cloud.ServiceOptions;
2224
import java.io.ByteArrayOutputStream;
2325
import java.io.IOException;
2426
import java.io.PrintStream;
@@ -57,4 +59,24 @@ public void testAuthExplicitNoPath() throws IOException {
5759
String output = bout.toString();
5860
assertTrue(output.contains("Buckets:"));
5961
}
62+
63+
@Test
64+
public void testAuthApiKey() throws IOException, IllegalStateException {
65+
String projectId = ServiceOptions.getDefaultProjectId();
66+
String keyDisplayName = "Test API Key";
67+
String service = "language.googleapis.com";
68+
String method = "google.cloud.language.v2.LanguageService.AnalyzeSentiment";
69+
Key apiKey = null;
70+
try {
71+
apiKey = AuthTestUtils.createTestApiKey(projectId, keyDisplayName, service, method);
72+
73+
String output = ApiKeyAuthExample.authenticateUsingApiKey(apiKey.getKeyString());
74+
75+
assertTrue(output.contains("magnitude:"));
76+
} finally {
77+
if (apiKey != null) {
78+
AuthTestUtils.deleteTestApiKey(apiKey.getName());
79+
}
80+
}
81+
}
6082
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Copyright 2024 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 com.google.cloud.auth.samples;
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.TimeUnit;
27+
28+
/**
29+
* Utility methods to setup data for IT auth tests.
30+
*/
31+
public class AuthTestUtils {
32+
33+
public static Key createTestApiKey(
34+
String projectId, String keyDisplayName, String service, String method)
35+
throws IllegalStateException {
36+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
37+
Key key =
38+
Key.newBuilder()
39+
.setDisplayName(keyDisplayName)
40+
.setRestrictions(
41+
Restrictions.newBuilder()
42+
.addApiTargets(
43+
ApiTarget.newBuilder().setService(service).addMethods(method).build())
44+
.build())
45+
.build();
46+
47+
CreateKeyRequest createKeyRequest =
48+
CreateKeyRequest.newBuilder()
49+
// API keys can only be global.
50+
.setParent(LocationName.of(projectId, "global").toString())
51+
.setKey(key)
52+
.build();
53+
return apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);
54+
} catch (Exception e) {
55+
throw new IllegalStateException("Error trying to create API Key " + e.getMessage());
56+
}
57+
}
58+
59+
public static void deleteTestApiKey(String keyName) throws IOException {
60+
try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
61+
apiKeysClient.deleteKeyAsync(keyName);
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)