Both OIDC and SAML are supported. The executable must adhere to a specific response format * defined below. * - *
The executable should print out the 3rd party token to STDOUT in JSON format. This is not - * required when an output_file is specified in the credential source, with the expectation being - * that the output file will contain the JSON response instead. + *
The executable must print out the 3rd party token to STDOUT in JSON format. When an + * output_file is specified in the credential configuration, the executable must also handle writing + * the JSON response to this file. * *
* OIDC response sample: @@ -85,6 +85,9 @@ * "message": "Error message." * } * + *The `expiration_time` field in the JSON response is only required for successful + * responses when an output file was specified in the credential configuration. + * * The auth libraries will populate certain environment variables that will be accessible by the * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and diff --git a/oauth2_http/java/com/google/auth/oauth2/PluggableAuthHandler.java b/oauth2_http/java/com/google/auth/oauth2/PluggableAuthHandler.java index 24b0978cd..6d62d6911 100644 --- a/oauth2_http/java/com/google/auth/oauth2/PluggableAuthHandler.java +++ b/oauth2_http/java/com/google/auth/oauth2/PluggableAuthHandler.java @@ -112,6 +112,18 @@ public String retrieveTokenFromExecutable(ExecutableOptions options) throws IOEx executableResponse = getExecutableResponse(options); } + // If an output file is specified, successful responses must contain the `expiration_time` + // field. + if (options.getOutputFilePath() != null + && !options.getOutputFilePath().isEmpty() + && executableResponse.isSuccessful() + && executableResponse.getExpirationTime() == null) { + throw new PluggableAuthException( + "INVALID_EXECUTABLE_RESPONSE", + "The executable response must contain the `expiration_time` field for successful responses when an " + + "output_file has been specified in the configuration."); + } + // The executable response includes a version. Validate that the version is compatible // with the library. if (executableResponse.getVersion() > EXECUTABLE_SUPPORTED_MAX_VERSION) { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java index b6f85684a..7c8fec60d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java @@ -60,12 +60,27 @@ void constructor_successOidcResponse() throws IOException { assertTrue(response.isSuccessful()); assertTrue(response.isValid()); - assertEquals(1, response.getVersion()); + assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); assertEquals(TOKEN_TYPE_OIDC, response.getTokenType()); assertEquals(ID_TOKEN, response.getSubjectToken()); assertEquals( Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); - assertEquals(1, response.getVersion()); + } + + @Test + void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { + GenericJson jsonResponse = buildOidcResponse(); + jsonResponse.remove("expiration_time"); + + ExecutableResponse response = new ExecutableResponse(jsonResponse); + + assertTrue(response.isSuccessful()); + assertTrue(response.isValid()); + assertFalse(response.isExpired()); + assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); + assertEquals(TOKEN_TYPE_OIDC, response.getTokenType()); + assertEquals(ID_TOKEN, response.getSubjectToken()); + assertNull(response.getExpirationTime()); } @Test @@ -81,17 +96,33 @@ void constructor_successSamlResponse() throws IOException { Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); } + @Test + void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { + GenericJson jsonResponse = buildSamlResponse(); + jsonResponse.remove("expiration_time"); + + ExecutableResponse response = new ExecutableResponse(jsonResponse); + + assertTrue(response.isSuccessful()); + assertTrue(response.isValid()); + assertFalse(response.isExpired()); + assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); + assertEquals(TOKEN_TYPE_SAML, response.getTokenType()); + assertEquals(SAML_RESPONSE, response.getSubjectToken()); + assertNull(response.getExpirationTime()); + } + @Test void constructor_validErrorResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildErrorResponse()); assertFalse(response.isSuccessful()); assertFalse(response.isValid()); - assertTrue(response.isExpired()); + assertFalse(response.isExpired()); assertNull(response.getSubjectToken()); assertNull(response.getTokenType()); assertNull(response.getExpirationTime()); - assertEquals(1, response.getVersion()); + assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); assertEquals("401", response.getErrorCode()); assertEquals("Caller not authorized.", response.getErrorMessage()); } @@ -189,23 +220,6 @@ void constructor_successResponseMissingTokenTypeField_throws() { exception.getMessage()); } - @Test - void constructor_successResponseMissingExpirationTimeField_throws() { - GenericJson jsonResponse = buildOidcResponse(); - jsonResponse.remove("expiration_time"); - - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " - + "`expiration_time` field.", - exception.getMessage()); - } - @Test void constructor_samlResponseMissingSubjectToken_throws() { GenericJson jsonResponse = buildSamlResponse(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index 1b2b53a1c..75b88dcfa 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -196,8 +196,7 @@ void fromJson_identityPoolCredentialsWorkforce() { assertEquals("subjectTokenType", credential.getSubjectTokenType()); assertEquals(STS_URL, credential.getTokenUrl()); assertEquals("tokenInfoUrl", credential.getTokenInfoUrl()); - assertEquals( - "userProject", ((IdentityPoolCredentials) credential).getWorkforcePoolUserProject()); + assertEquals("userProject", credential.getWorkforcePoolUserProject()); assertNotNull(credential.getCredentialSource()); } @@ -235,6 +234,30 @@ void fromJson_pluggableAuthCredentials() { assertNull(source.getOutputFilePath()); } + @Test + void fromJson_pluggableAuthCredentialsWorkforce() { + ExternalAccountCredentials credential = + ExternalAccountCredentials.fromJson( + buildJsonPluggableAuthWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); + + assertTrue(credential instanceof PluggableAuthCredentials); + assertEquals( + "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider", + credential.getAudience()); + assertEquals("subjectTokenType", credential.getSubjectTokenType()); + assertEquals(STS_URL, credential.getTokenUrl()); + assertEquals("tokenInfoUrl", credential.getTokenInfoUrl()); + assertEquals("userProject", credential.getWorkforcePoolUserProject()); + + assertNotNull(credential.getCredentialSource()); + + PluggableAuthCredentialSource source = + (PluggableAuthCredentialSource) credential.getCredentialSource(); + assertEquals("command", source.getCommand()); + assertEquals(30000, source.getTimeoutMs()); // Default timeout is 30s. + assertNull(source.getOutputFilePath()); + } + @Test void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() { GenericJson json = buildJsonPluggableAuthCredential(); @@ -502,25 +525,35 @@ void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOExc @Test void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() throws IOException { - ExternalAccountCredentials credential = + ExternalAccountCredentials identityPoolCredential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), transportFactory); - StsTokenExchangeRequest stsTokenExchangeRequest = - StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); + ExternalAccountCredentials pluggableAuthCredential = + ExternalAccountCredentials.fromJson( + buildJsonPluggableAuthWorkforceCredential(), transportFactory); - AccessToken accessToken = - credential.exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest); + List
credentials = + Arrays.asList(identityPoolCredential, pluggableAuthCredential); - assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue()); + for (int i = 0; i < credentials.size(); i++) { + StsTokenExchangeRequest stsTokenExchangeRequest = + StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); - // Validate internal options set. - Map query = - TestUtils.parseQuery(transportFactory.transport.getLastRequest().getContentAsString()); - GenericJson internalOptions = new GenericJson(); - internalOptions.setFactory(OAuth2Utils.JSON_FACTORY); - internalOptions.put("userProject", "userProject"); - assertEquals(internalOptions.toString(), query.get("options")); + AccessToken accessToken = + credentials.get(i).exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest); + + assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue()); + + // Validate internal options set. + Map query = + TestUtils.parseQuery(transportFactory.transport.getLastRequest().getContentAsString()); + GenericJson internalOptions = new GenericJson(); + internalOptions.setFactory(OAuth2Utils.JSON_FACTORY); + internalOptions.put("userProject", "userProject"); + assertEquals(internalOptions.toString(), query.get("options")); + assertEquals(i + 1, transportFactory.transport.getRequests().size()); + } } @Test @@ -813,6 +846,14 @@ private GenericJson buildJsonPluggableAuthCredential() { return json; } + private GenericJson buildJsonPluggableAuthWorkforceCredential() { + GenericJson json = buildJsonPluggableAuthCredential(); + json.put( + "audience", "//iam.googleapis.com/locations/global/workforcePools/pool/providers/provider"); + json.put("workforce_pool_user_project", "userProject"); + return json; + } + static class TestExternalAccountCredentials extends ExternalAccountCredentials { static class TestCredentialSource extends IdentityPoolCredentials.IdentityPoolCredentialSource { protected TestCredentialSource(Map credentialSourceMap) { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java index 4e630d49c..d751c403f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java @@ -51,7 +51,9 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; @@ -218,6 +220,216 @@ void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedExcept assertEquals("Caller not authorized.", e.getErrorDescription()); } + @Test + void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() + throws InterruptedException, IOException { + TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); + environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); + + // Expected environment mappings. + HashMap expectedMap = new HashMap<>(); + expectedMap.putAll(DEFAULT_OPTIONS.getEnvironmentMap()); + + Map currentEnv = new HashMap<>(); + + // Mock executable handling. + Process mockProcess = Mockito.mock(Process.class); + when(mockProcess.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true); + when(mockProcess.exitValue()).thenReturn(EXIT_CODE_SUCCESS); + + // Remove expiration_time from the executable responses. + GenericJson oidcResponse = buildOidcResponse(); + oidcResponse.remove("expiration_time"); + + GenericJson samlResponse = buildSamlResponse(); + samlResponse.remove("expiration_time"); + + List responses = Arrays.asList(oidcResponse, samlResponse); + for (int i = 0; i < responses.size(); i++) { + when(mockProcess.getInputStream()) + .thenReturn( + new ByteArrayInputStream( + responses.get(i).toString().getBytes(StandardCharsets.UTF_8))); + + InternalProcessBuilder processBuilder = + buildInternalProcessBuilder( + currentEnv, mockProcess, DEFAULT_OPTIONS.getExecutableCommand()); + + PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); + + // Call retrieveTokenFromExecutable(). + String token = handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS); + + verify(mockProcess, times(i + 1)).destroy(); + verify(mockProcess, times(i + 1)) + .waitFor( + eq(Long.valueOf(DEFAULT_OPTIONS.getExecutableTimeoutMs())), + eq(TimeUnit.MILLISECONDS)); + + if (responses.get(i).equals(oidcResponse)) { + assertEquals(ID_TOKEN, token); + } else { + assertEquals(SAML_RESPONSE, token); + } + + // Current env map should have the mappings from options. + assertEquals(2, currentEnv.size()); + assertEquals(expectedMap, currentEnv); + } + } + + @Test + void + retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFieldWithOutputFileSpecified_throws() + throws InterruptedException, IOException { + TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); + environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); + + // Options with output file specified. + ExecutableOptions options = + new ExecutableOptions() { + @Override + public String getExecutableCommand() { + return "/path/to/executable"; + } + + @Override + public Map getEnvironmentMap() { + return ImmutableMap.of(); + } + + @Override + public int getExecutableTimeoutMs() { + return 30000; + } + + @Override + public String getOutputFilePath() { + return "/path/to/output/file"; + } + }; + + // Mock executable handling. + Process mockProcess = Mockito.mock(Process.class); + when(mockProcess.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(true); + when(mockProcess.exitValue()).thenReturn(EXIT_CODE_SUCCESS); + + // Remove expiration_time from the executable responses. + GenericJson oidcResponse = buildOidcResponse(); + oidcResponse.remove("expiration_time"); + + GenericJson samlResponse = buildSamlResponse(); + samlResponse.remove("expiration_time"); + + List responses = Arrays.asList(oidcResponse, samlResponse); + for (int i = 0; i < responses.size(); i++) { + when(mockProcess.getInputStream()) + .thenReturn( + new ByteArrayInputStream( + responses.get(i).toString().getBytes(StandardCharsets.UTF_8))); + + InternalProcessBuilder processBuilder = + buildInternalProcessBuilder(new HashMap<>(), mockProcess, options.getExecutableCommand()); + + PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); + + // Call retrieveTokenFromExecutable() should throw an exception as the STDOUT response + // is missing + // the `expiration_time` field and an output file was specified in the configuration. + PluggableAuthException exception = + assertThrows( + PluggableAuthException.class, + () -> handler.retrieveTokenFromExecutable(options), + "Exception should be thrown."); + + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " + + "`expiration_time` field for successful responses when an output_file has been specified in the" + + " configuration.", + exception.getMessage()); + + verify(mockProcess, times(i + 1)).destroy(); + verify(mockProcess, times(i + 1)) + .waitFor(eq(Long.valueOf(options.getExecutableTimeoutMs())), eq(TimeUnit.MILLISECONDS)); + } + } + + @Test + void retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() + throws InterruptedException, IOException { + TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); + environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); + + // Build output_file. + File file = File.createTempFile("output_file", /* suffix= */ null, /* directory= */ null); + file.deleteOnExit(); + + // Options with output file specified. + ExecutableOptions options = + new ExecutableOptions() { + @Override + public String getExecutableCommand() { + return "/path/to/executable"; + } + + @Override + public Map getEnvironmentMap() { + return ImmutableMap.of(); + } + + @Override + public int getExecutableTimeoutMs() { + return 30000; + } + + @Override + public String getOutputFilePath() { + return file.getAbsolutePath(); + } + }; + + // Mock executable handling that does nothing since we are using the output file. + Process mockProcess = Mockito.mock(Process.class); + InternalProcessBuilder processBuilder = + buildInternalProcessBuilder(new HashMap<>(), mockProcess, options.getExecutableCommand()); + + // Remove expiration_time from the executable responses. + GenericJson oidcResponse = buildOidcResponse(); + oidcResponse.remove("expiration_time"); + + GenericJson samlResponse = buildSamlResponse(); + samlResponse.remove("expiration_time"); + + List responses = Arrays.asList(oidcResponse, samlResponse); + for (GenericJson json : responses) { + OAuth2Utils.writeInputStreamToFile( + new ByteArrayInputStream(json.toString().getBytes(StandardCharsets.UTF_8)), + file.getAbsolutePath()); + + PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); + + // Call retrieveTokenFromExecutable() which should throw an exception as the output file + // response is missing + // the `expiration_time` field. + PluggableAuthException exception = + assertThrows( + PluggableAuthException.class, + () -> handler.retrieveTokenFromExecutable(options), + "Exception should be thrown."); + + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " + + "`expiration_time` field for successful responses when an output_file has been specified in the" + + " configuration.", + exception.getMessage()); + + // Validate executable not invoked. + verify(mockProcess, times(0)).destroyForcibly(); + verify(mockProcess, times(0)) + .waitFor(eq(Long.valueOf(options.getExecutableTimeoutMs())), eq(TimeUnit.MILLISECONDS)); + } + } + @Test void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() throws IOException, InterruptedException { diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index fc6293357..a604d4986 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -5,7 +5,7 @@ diff --git a/pom.xml b/pom.xml index 664e1eb08..20554ffad 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ com.google.auth google-auth-library-parent -1.9.0 +1.10.0 ../pom.xml 4.0.0 com.google.auth google-auth-library-parent -1.9.0 +1.10.0 pom Google Auth Library for Java Client libraries providing authentication and @@ -272,7 +272,7 @@ org.apache.maven.plugins maven-site-plugin -3.12.0 +3.12.1 diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml new file mode 100644 index 000000000..a41ee3f7f --- /dev/null +++ b/samples/snippets/pom.xml @@ -0,0 +1,83 @@ + true + + 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:"); + Page4.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 +26.0.0 +pom +import ++ + + ++ + + +com.google.auth +google-auth-library-oauth2-http +1.9.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.2 +test ++ + +truth +com.google.truth +test +1.1.3 +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