diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml new file mode 100644 index 000000000..d0ff21c82 --- /dev/null +++ b/samples/snippets/pom.xml @@ -0,0 +1,83 @@ + + 4.0.0 + com.google.auth.samples + authsamples + 1.0.0 + auth-samples + + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 1.8 + 1.8 + UTF-8 + + + + + + + + com.google.cloud + libraries-bom + 25.0.0 + pom + import + + + + + + + + + com.google.auth + google-auth-library-oauth2-http + 1.3.0 + + + + + com.google.cloud + google-iam-admin + 1.2.1 + + + + + com.google.cloud + google-cloud-compute + + + com.google.cloud + google-cloud-storage + + + + + junit + junit + 4.13.1 + test + + + truth + com.google.truth + test + 1.1.3 + + + + + + diff --git a/samples/snippets/src/main/java/AuthenticateExplicit.java b/samples/snippets/src/main/java/AuthenticateExplicit.java new file mode 100644 index 000000000..ccd189db9 --- /dev/null +++ b/samples/snippets/src/main/java/AuthenticateExplicit.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// [START auth_cloud_explicit_adc] + +import com.google.api.gax.paging.Page; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import java.io.IOException; +import java.security.GeneralSecurityException; + +public class AuthenticateExplicit { + + public static void main(String[] args) throws IOException, GeneralSecurityException { + // TODO(Developer): + // 1. Replace the project variable below. + // 2. Make sure you have the necessary permission to list storage buckets + // "storage.buckets.list" + + String projectId = "your-google-cloud-project-id"; + + authenticateExplicit(projectId); + } + + // List storage buckets by authenticating with ADC. + public static void authenticateExplicit(String projectId) throws IOException { + // Construct the GoogleCredentials object which obtains the default configuration from your + // working environment. + // GoogleCredentials.getApplicationDefault() will give you ComputeEngineCredentials + // if you are on a GCE (or other metadata server supported environments). + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); + // If you are authenticating to a Cloud API, you can let the library include the default scope, + // https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained + // permissions for Cloud. + // If you need to provide a scope, specify it as follows: + // GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + // .createScoped(scope); + // For more information on scopes to use, + // see: https://developers.google.com/identity/protocols/oauth2/scopes + + // Construct the Storage client. + Storage storage = + StorageOptions.newBuilder() + .setCredentials(credentials) + .setProjectId(projectId) + .build() + .getService(); + + System.out.println("Buckets:"); + Page buckets = storage.list(); + for (Bucket bucket : buckets.iterateAll()) { + System.out.println(bucket.toString()); + } + System.out.println("Listed all storage buckets."); + } +} +// [END auth_cloud_explicit_adc] diff --git a/samples/snippets/src/main/java/AuthenticateImplicitWithAdc.java b/samples/snippets/src/main/java/AuthenticateImplicitWithAdc.java new file mode 100644 index 000000000..9b69429ef --- /dev/null +++ b/samples/snippets/src/main/java/AuthenticateImplicitWithAdc.java @@ -0,0 +1,60 @@ +/* + * Copyright 2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// [START auth_cloud_implicit_adc] + +import com.google.cloud.compute.v1.Instance; +import com.google.cloud.compute.v1.InstancesClient; +import java.io.IOException; + +public class AuthenticateImplicitWithAdc { + + public static void main(String[] args) throws IOException { + // TODO(Developer): + // 1. Before running this sample, + // set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc + // 2. Replace the project variable below. + // 3. Make sure that the user account or service account that you are using + // has the required permissions. For this sample, you must have "compute.instances.list". + String projectId = "your-google-cloud-project-id"; + authenticateImplicitWithAdc(projectId); + } + + // When interacting with Google Cloud Client libraries, the library can auto-detect the + // credentials to use. + public static void authenticateImplicitWithAdc(String project) throws IOException { + + String zone = "us-central1-a"; + // This snippet demonstrates how to list instances. + // *NOTE*: Replace the client created below with the client required for your application. + // Note that the credentials are not specified when constructing the client. + // Hence, the client library will look for credentials using ADC. + // + // 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 `instancesClient.close()` method on the client to safely + // clean up any remaining background resources. + try (InstancesClient instancesClient = InstancesClient.create()) { + // Set the project and zone to retrieve instances present in the zone. + System.out.printf("Listing instances from %s in %s:", project, zone); + for (Instance zoneInstance : instancesClient.list(project, zone).iterateAll()) { + System.out.println(zoneInstance.getName()); + } + System.out.println("####### Listing instances complete #######"); + } + } +} +// [END auth_cloud_implicit_adc] diff --git a/samples/snippets/src/main/java/IdTokenFromImpersonatedCredentials.java b/samples/snippets/src/main/java/IdTokenFromImpersonatedCredentials.java new file mode 100644 index 000000000..b348e3976 --- /dev/null +++ b/samples/snippets/src/main/java/IdTokenFromImpersonatedCredentials.java @@ -0,0 +1,87 @@ +/* + * Copyright 2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// [auth_cloud_idtoken_impersonated_credentials] + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.IdTokenCredentials; +import com.google.auth.oauth2.IdTokenProvider.Option; +import com.google.auth.oauth2.ImpersonatedCredentials; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public class IdTokenFromImpersonatedCredentials { + + public static void main(String[] args) throws IOException { + // TODO(Developer): Replace the below variables before running the code. + + // Provide the scopes that you might need to request to access Google APIs, + // depending on the level of access you need. + // The best practice is to use the cloud-wide scope and use IAM to narrow the permissions. + // https://cloud.google.com/docs/authentication#authorization_for_services + // For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes + String scope = "https://www.googleapis.com/auth/cloud-platform"; + + // The service name for which the id token is requested. Service name refers to the + // logical identifier of an API service, such as "pubsub.googleapis.com". + String targetAudience = "iap.googleapis.com"; + + // The name of the privilege-bearing service account for whom the credential is created. + String impersonatedServiceAccount = "name@project.service.gserviceaccount.com"; + + getIdTokenUsingOAuth2(impersonatedServiceAccount, scope, targetAudience); + } + + // Use a service account (SA1) to impersonate as another service account (SA2) and obtain id token + // for the impersonated account. + // To obtain token for SA2, SA1 should have the "roles/iam.serviceAccountTokenCreator" permission + // on SA2. + public static void getIdTokenUsingOAuth2( + String impersonatedServiceAccount, String scope, String targetAudience) throws IOException { + + // Construct the GoogleCredentials object which obtains the default configuration from your + // working environment. + GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); + + // delegates: The chained list of delegates required to grant the final accessToken. + // For more information, see: + // https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions + // Delegate is NOT USED here. + List delegates = null; + + // Create the impersonated credential. + ImpersonatedCredentials impersonatedCredentials = + ImpersonatedCredentials.create( + googleCredentials, impersonatedServiceAccount, delegates, Arrays.asList(scope), 300); + + // Set the impersonated credential, target audience and token options. + IdTokenCredentials idTokenCredentials = + IdTokenCredentials.newBuilder() + .setIdTokenProvider(impersonatedCredentials) + .setTargetAudience(targetAudience) + // Setting this will include email in the id token. + .setOptions(Arrays.asList(Option.INCLUDE_EMAIL)) + .build(); + + // Get the ID token. + // Once you've obtained the ID token, use it to make an authenticated call + // to the target audience. + String idToken = idTokenCredentials.refreshAccessToken().getTokenValue(); + System.out.println("Generated ID token."); + } +} +// [auth_cloud_idtoken_impersonated_credentials] diff --git a/samples/snippets/src/main/java/IdTokenFromMetadataServer.java b/samples/snippets/src/main/java/IdTokenFromMetadataServer.java new file mode 100644 index 000000000..3358ccdbe --- /dev/null +++ b/samples/snippets/src/main/java/IdTokenFromMetadataServer.java @@ -0,0 +1,61 @@ +/* + * Copyright 2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// [START auth_cloud_idtoken_metadata_server] + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.IdTokenCredentials; +import com.google.auth.oauth2.IdTokenProvider; +import com.google.auth.oauth2.IdTokenProvider.Option; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Arrays; + +public class IdTokenFromMetadataServer { + + public static void main(String[] args) throws IOException, GeneralSecurityException { + // TODO(Developer): Replace the below variables before running the code. + + // The url or target audience to obtain the ID token for. + String url = "http://www.abc.com"; + + getIdTokenFromMetadataServer(url); + } + + // Use the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,) + // environment to create an identity token and add it to the HTTP request as part of an + // Authorization header. + public static void getIdTokenFromMetadataServer(String url) throws IOException { + // Construct the GoogleCredentials object which obtains the default configuration from your + // working environment. + GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); + + IdTokenCredentials idTokenCredentials = + IdTokenCredentials.newBuilder() + .setIdTokenProvider((IdTokenProvider) googleCredentials) + .setTargetAudience(url) + // Setting the ID token options. + .setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE)) + .build(); + + // Get the ID token. + // Once you've obtained the ID token, use it to make an authenticated call + // to the target audience. + String idToken = idTokenCredentials.refreshAccessToken().getTokenValue(); + System.out.println("Generated ID token."); + } +} +// [END auth_cloud_idtoken_metadata_server] diff --git a/samples/snippets/src/main/java/IdTokenFromServiceAccount.java b/samples/snippets/src/main/java/IdTokenFromServiceAccount.java new file mode 100644 index 000000000..232288805 --- /dev/null +++ b/samples/snippets/src/main/java/IdTokenFromServiceAccount.java @@ -0,0 +1,75 @@ +/* + * Copyright 2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// [START auth_cloud_idtoken_service_account] + +import com.google.auth.oauth2.IdToken; +import com.google.auth.oauth2.IdTokenProvider.Option; +import com.google.auth.oauth2.ServiceAccountCredentials; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutionException; + +public class IdTokenFromServiceAccount { + + public static void main(String[] args) + throws IOException, ExecutionException, InterruptedException, GeneralSecurityException { + // TODO(Developer): Replace the below variables before running the code. + + // *NOTE*: + // Using service account keys introduces risk; they are long-lived, and can be used by anyone + // that obtains the key. Proper rotation and storage reduce this risk but do not eliminate it. + // For these reasons, you should consider an alternative approach that + // does not use a service account key. Several alternatives to service account keys + // are described here: + // https://cloud.google.com/docs/authentication/external/set-up-adc + + // Path to the service account json credential file. + String jsonCredentialPath = "path-to-json-credential-file"; + + // The url or target audience to obtain the ID token for. + String targetAudience = "http://www.abc.com"; + + getIdTokenFromServiceAccount(jsonCredentialPath, targetAudience); + } + + public static void getIdTokenFromServiceAccount(String jsonCredentialPath, String targetAudience) + throws IOException { + + // Initialize the Service Account Credentials class with the path to the json file. + ServiceAccountCredentials serviceAccountCredentials = + ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialPath)); + + // Obtain the id token by providing the target audience. + // tokenOption: Enum of various credential-specific options to apply to the token. Applicable + // only for credentials obtained through Compute Engine or Impersonation. + List