Skip to content

Commit 32c717f

Browse files
Sita04gcf-owl-bot[bot]Shabirmean
authored
docs(samples): added auth samples and tests (#927)
* docs(samples): added client code for idtoken, adc and metadata server * docs(samples): added authexplicit and copyright * docs(samples): add auth with metadata server * docs(samples): minor refactoring and added tests * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * refactored acc to review comments * refactored acc to review comments * refactored acc to review comments * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * minor comment update * modified google id token verification and removed third party dependency * removed third party deps from pom * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * included comment about verifying Google ID tokens * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Shabir Mohamed Abdul Samadh <[email protected]>
1 parent 7964a58 commit 32c717f

8 files changed

+646
-0
lines changed

samples/snippets/pom.xml

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0">
2+
<modelVersion>4.0.0</modelVersion>
3+
<groupId>com.google.auth.samples</groupId>
4+
<artifactId>authsamples</artifactId>
5+
<version>1.0.0</version>
6+
<name>auth-samples</name>
7+
8+
9+
<!--
10+
The parent pom defines common style checks and testing strategies for our samples.
11+
Removing or replacing it should not affect the execution of the samples in any way.
12+
-->
13+
<parent>
14+
<groupId>com.google.cloud.samples</groupId>
15+
<artifactId>shared-configuration</artifactId>
16+
<version>1.2.0</version>
17+
</parent>
18+
19+
<properties>
20+
<maven.compiler.target>1.8</maven.compiler.target>
21+
<maven.compiler.source>1.8</maven.compiler.source>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
</properties>
24+
25+
<!-- START dependencies -->
26+
<!-- Using libraries-bom to manage versions.
27+
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
28+
<dependencyManagement>
29+
<dependencies>
30+
<dependency>
31+
<groupId>com.google.cloud</groupId>
32+
<artifactId>libraries-bom</artifactId>
33+
<version>25.0.0</version>
34+
<type>pom</type>
35+
<scope>import</scope>
36+
</dependency>
37+
</dependencies>
38+
</dependencyManagement>
39+
40+
41+
<dependencies>
42+
<!-- OAuth dependency-->
43+
<dependency>
44+
<groupId>com.google.auth</groupId>
45+
<artifactId>google-auth-library-oauth2-http</artifactId>
46+
<version>1.3.0</version>
47+
</dependency>
48+
49+
<!-- IAM dependency-->
50+
<dependency>
51+
<groupId>com.google.cloud</groupId>
52+
<artifactId>google-iam-admin</artifactId>
53+
<version>1.2.1</version>
54+
</dependency>
55+
56+
<!-- GCloud dependency-->
57+
<dependency>
58+
<groupId>com.google.cloud</groupId>
59+
<artifactId>google-cloud-compute</artifactId>
60+
</dependency>
61+
<dependency>
62+
<groupId>com.google.cloud</groupId>
63+
<artifactId>google-cloud-storage</artifactId>
64+
</dependency>
65+
66+
<!-- Test dependencies-->
67+
<dependency>
68+
<groupId>junit</groupId>
69+
<artifactId>junit</artifactId>
70+
<version>4.13.1</version>
71+
<scope>test</scope>
72+
</dependency>
73+
<dependency>
74+
<artifactId>truth</artifactId>
75+
<groupId>com.google.truth</groupId>
76+
<scope>test</scope>
77+
<version>1.1.3</version>
78+
</dependency>
79+
80+
</dependencies>
81+
82+
</project>
83+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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_explicit_adc]
18+
19+
import com.google.api.gax.paging.Page;
20+
import com.google.auth.oauth2.GoogleCredentials;
21+
import com.google.cloud.storage.Bucket;
22+
import com.google.cloud.storage.Storage;
23+
import com.google.cloud.storage.StorageOptions;
24+
import java.io.IOException;
25+
import java.security.GeneralSecurityException;
26+
27+
public class AuthenticateExplicit {
28+
29+
public static void main(String[] args) throws IOException, GeneralSecurityException {
30+
// TODO(Developer):
31+
// 1. Replace the project variable below.
32+
// 2. Make sure you have the necessary permission to list storage buckets
33+
// "storage.buckets.list"
34+
35+
String projectId = "your-google-cloud-project-id";
36+
37+
authenticateExplicit(projectId);
38+
}
39+
40+
// List storage buckets by authenticating with ADC.
41+
public static void authenticateExplicit(String projectId) throws IOException {
42+
// Construct the GoogleCredentials object which obtains the default configuration from your
43+
// working environment.
44+
// GoogleCredentials.getApplicationDefault() will give you ComputeEngineCredentials
45+
// if you are on a GCE (or other metadata server supported environments).
46+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
47+
// If you are authenticating to a Cloud API, you can let the library include the default scope,
48+
// https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained
49+
// permissions for Cloud.
50+
// If you need to provide a scope, specify it as follows:
51+
// GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
52+
// .createScoped(scope);
53+
// For more information on scopes to use,
54+
// see: https://developers.google.com/identity/protocols/oauth2/scopes
55+
56+
// Construct the Storage client.
57+
Storage storage =
58+
StorageOptions.newBuilder()
59+
.setCredentials(credentials)
60+
.setProjectId(projectId)
61+
.build()
62+
.getService();
63+
64+
System.out.println("Buckets:");
65+
Page<Bucket> buckets = storage.list();
66+
for (Bucket bucket : buckets.iterateAll()) {
67+
System.out.println(bucket.toString());
68+
}
69+
System.out.println("Listed all storage buckets.");
70+
}
71+
}
72+
// [END auth_cloud_explicit_adc]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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_implicit_adc]
18+
19+
import com.google.cloud.compute.v1.Instance;
20+
import com.google.cloud.compute.v1.InstancesClient;
21+
import java.io.IOException;
22+
23+
public class AuthenticateImplicitWithAdc {
24+
25+
public static void main(String[] args) throws IOException {
26+
// TODO(Developer):
27+
// 1. Before running this sample,
28+
// set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
29+
// 2. Replace the project variable below.
30+
// 3. Make sure that the user account or service account that you are using
31+
// has the required permissions. For this sample, you must have "compute.instances.list".
32+
String projectId = "your-google-cloud-project-id";
33+
authenticateImplicitWithAdc(projectId);
34+
}
35+
36+
// When interacting with Google Cloud Client libraries, the library can auto-detect the
37+
// credentials to use.
38+
public static void authenticateImplicitWithAdc(String project) throws IOException {
39+
40+
String zone = "us-central1-a";
41+
// This snippet demonstrates how to list instances.
42+
// *NOTE*: Replace the client created below with the client required for your application.
43+
// Note that the credentials are not specified when constructing the client.
44+
// Hence, the client library will look for credentials using ADC.
45+
//
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 `instancesClient.close()` method on the client to safely
49+
// clean up any remaining background resources.
50+
try (InstancesClient instancesClient = InstancesClient.create()) {
51+
// Set the project and zone to retrieve instances present in the zone.
52+
System.out.printf("Listing instances from %s in %s:", project, zone);
53+
for (Instance zoneInstance : instancesClient.list(project, zone).iterateAll()) {
54+
System.out.println(zoneInstance.getName());
55+
}
56+
System.out.println("####### Listing instances complete #######");
57+
}
58+
}
59+
}
60+
// [END auth_cloud_implicit_adc]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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+
// [auth_cloud_idtoken_impersonated_credentials]
18+
19+
import com.google.auth.oauth2.GoogleCredentials;
20+
import com.google.auth.oauth2.IdTokenCredentials;
21+
import com.google.auth.oauth2.IdTokenProvider.Option;
22+
import com.google.auth.oauth2.ImpersonatedCredentials;
23+
import java.io.IOException;
24+
import java.util.Arrays;
25+
import java.util.List;
26+
27+
public class IdTokenFromImpersonatedCredentials {
28+
29+
public static void main(String[] args) throws IOException {
30+
// TODO(Developer): Replace the below variables before running the code.
31+
32+
// Provide the scopes that you might need to request to access Google APIs,
33+
// depending on the level of access you need.
34+
// The best practice is to use the cloud-wide scope and use IAM to narrow the permissions.
35+
// https://cloud.google.com/docs/authentication#authorization_for_services
36+
// For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes
37+
String scope = "https://www.googleapis.com/auth/cloud-platform";
38+
39+
// The service name for which the id token is requested. Service name refers to the
40+
// logical identifier of an API service, such as "pubsub.googleapis.com".
41+
String targetAudience = "iap.googleapis.com";
42+
43+
// The name of the privilege-bearing service account for whom the credential is created.
44+
String impersonatedServiceAccount = "[email protected]";
45+
46+
getIdTokenUsingOAuth2(impersonatedServiceAccount, scope, targetAudience);
47+
}
48+
49+
// Use a service account (SA1) to impersonate as another service account (SA2) and obtain id token
50+
// for the impersonated account.
51+
// To obtain token for SA2, SA1 should have the "roles/iam.serviceAccountTokenCreator" permission
52+
// on SA2.
53+
public static void getIdTokenUsingOAuth2(
54+
String impersonatedServiceAccount, String scope, String targetAudience) throws IOException {
55+
56+
// Construct the GoogleCredentials object which obtains the default configuration from your
57+
// working environment.
58+
GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();
59+
60+
// delegates: The chained list of delegates required to grant the final accessToken.
61+
// For more information, see:
62+
// https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions
63+
// Delegate is NOT USED here.
64+
List<String> delegates = null;
65+
66+
// Create the impersonated credential.
67+
ImpersonatedCredentials impersonatedCredentials =
68+
ImpersonatedCredentials.create(
69+
googleCredentials, impersonatedServiceAccount, delegates, Arrays.asList(scope), 300);
70+
71+
// Set the impersonated credential, target audience and token options.
72+
IdTokenCredentials idTokenCredentials =
73+
IdTokenCredentials.newBuilder()
74+
.setIdTokenProvider(impersonatedCredentials)
75+
.setTargetAudience(targetAudience)
76+
// Setting this will include email in the id token.
77+
.setOptions(Arrays.asList(Option.INCLUDE_EMAIL))
78+
.build();
79+
80+
// Get the ID token.
81+
// Once you've obtained the ID token, use it to make an authenticated call
82+
// to the target audience.
83+
String idToken = idTokenCredentials.refreshAccessToken().getTokenValue();
84+
System.out.println("Generated ID token.");
85+
}
86+
}
87+
// [auth_cloud_idtoken_impersonated_credentials]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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_idtoken_metadata_server]
18+
19+
import com.google.auth.oauth2.GoogleCredentials;
20+
import com.google.auth.oauth2.IdTokenCredentials;
21+
import com.google.auth.oauth2.IdTokenProvider;
22+
import com.google.auth.oauth2.IdTokenProvider.Option;
23+
import java.io.IOException;
24+
import java.security.GeneralSecurityException;
25+
import java.util.Arrays;
26+
27+
public class IdTokenFromMetadataServer {
28+
29+
public static void main(String[] args) throws IOException, GeneralSecurityException {
30+
// TODO(Developer): Replace the below variables before running the code.
31+
32+
// The url or target audience to obtain the ID token for.
33+
String url = "http://www.abc.com";
34+
35+
getIdTokenFromMetadataServer(url);
36+
}
37+
38+
// Use the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,)
39+
// environment to create an identity token and add it to the HTTP request as part of an
40+
// Authorization header.
41+
public static void getIdTokenFromMetadataServer(String url) throws IOException {
42+
// Construct the GoogleCredentials object which obtains the default configuration from your
43+
// working environment.
44+
GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();
45+
46+
IdTokenCredentials idTokenCredentials =
47+
IdTokenCredentials.newBuilder()
48+
.setIdTokenProvider((IdTokenProvider) googleCredentials)
49+
.setTargetAudience(url)
50+
// Setting the ID token options.
51+
.setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE))
52+
.build();
53+
54+
// Get the ID token.
55+
// Once you've obtained the ID token, use it to make an authenticated call
56+
// to the target audience.
57+
String idToken = idTokenCredentials.refreshAccessToken().getTokenValue();
58+
System.out.println("Generated ID token.");
59+
}
60+
}
61+
// [END auth_cloud_idtoken_metadata_server]

0 commit comments

Comments
 (0)