Skip to content

Commit 2fdb794

Browse files
irataxySita04
andauthored
feat: add sample and test for getting an access token from an imperso… (GoogleCloudPlatform#8747)
* feat: add sample and test for getting an access token from an impersonated SA * fix checkstyle violations * setup secret for impersonated service account * fix lint check * add cleanup method to test --------- Co-authored-by: Sita Lakshmi Sangameswaran <sitalakshmi@google.com>
1 parent 44d4d18 commit 2fdb794

File tree

3 files changed

+147
-1
lines changed

3 files changed

+147
-1
lines changed

.kokoro/tests/run_tests.sh

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ if [[ "$SCRIPT_DEBUG" != "true" ]]; then
8282
"java-iam-samples-secrets.txt" \
8383
"java-scc-samples-secrets.txt" \
8484
"java-bigqueryconnection-samples-secrets.txt" \
85-
"java-bigquerydatatransfer-samples-secrets.txt")
85+
"java-bigquerydatatransfer-samples-secrets.txt" \
86+
"java-auth-samples-secrets.txt")
8687

8788
# create secret dir
8889
mkdir -p "${KOKORO_GFILE_DIR}/secrets"
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2023 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+
// [START auth_cloud_accesstoken_impersonated_credentials]
18+
19+
package com.google.cloud.auth.samples;
20+
21+
import com.google.auth.oauth2.GoogleCredentials;
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 AccessTokenFromImpersonatedCredentials {
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 access to Google APIs,
33+
// depending on the level of access you need.
34+
// This example uses the cloud-wide scope and uses IAM to narrow the permissions.
35+
// https://cloud.google.com/docs/authentication/external/authorization-gcp
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 name of the privilege-bearing service account for whom the credential is created.
40+
String impersonatedServiceAccount = "name@project.service.gserviceaccount.com";
41+
42+
getAccessToken(impersonatedServiceAccount, scope);
43+
}
44+
45+
// Use a service account (SA1) to impersonate another service account (SA2) and obtain an ID token
46+
// for the impersonated account.
47+
// To obtain a token for SA2, SA1 should have the "roles/iam.serviceAccountTokenCreator"
48+
// permission on SA2.
49+
public static void getAccessToken(
50+
String impersonatedServiceAccount, String scope) throws IOException {
51+
52+
// Construct the GoogleCredentials object which obtains the default configuration from your
53+
// working environment.
54+
GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();
55+
56+
// delegates: The chained list of delegates required to grant the final accessToken.
57+
// For more information, see:
58+
// https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions
59+
// Delegate is NOT USED here.
60+
List<String> delegates = null;
61+
62+
// Create the impersonated credential.
63+
ImpersonatedCredentials impersonatedCredentials =
64+
ImpersonatedCredentials.newBuilder()
65+
.setSourceCredentials(googleCredentials)
66+
.setTargetPrincipal(impersonatedServiceAccount)
67+
.setScopes(Arrays.asList(scope))
68+
.setLifetime(300)
69+
.setDelegates(delegates)
70+
.build();
71+
72+
// Get the OAuth2 token.
73+
// Once you've obtained the OAuth2 token, you can use it to make an authenticated call.
74+
impersonatedCredentials.refresh();
75+
String accessToken = impersonatedCredentials.getAccessToken().getTokenValue();
76+
System.out.println("Generated access token.");
77+
}
78+
}
79+
// [END auth_cloud_accesstoken_impersonated_credentials]
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright 2023 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 static org.junit.Assert.assertNotNull;
20+
import static org.junit.Assert.assertTrue;
21+
22+
import java.io.ByteArrayOutputStream;
23+
import java.io.IOException;
24+
import java.io.PrintStream;
25+
import org.junit.After;
26+
import org.junit.Before;
27+
import org.junit.Test;
28+
import org.junit.runner.RunWith;
29+
import org.junit.runners.JUnit4;
30+
31+
@RunWith(JUnit4.class)
32+
//CHECKSTYLE OFF: AbbreviationAsWordInName
33+
public class AccessTokenFromImpersonatedCredentialsIT {
34+
35+
//CHECKSTYLE ON: AbbreviationAsWordInName
36+
private static final String impersonatedServiceAccount =
37+
System.getenv("IMPERSONATED_SERVICE_ACCOUNT");
38+
private static final String scope = "https://www.googleapis.com/auth/cloud-platform";
39+
private final PrintStream originalOut = System.out;
40+
private ByteArrayOutputStream bout;
41+
private PrintStream out;
42+
private String credentials;
43+
44+
@Before
45+
public void setUp() {
46+
bout = new ByteArrayOutputStream();
47+
out = new PrintStream(bout);
48+
System.setOut(out);
49+
credentials = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
50+
assertNotNull(credentials);
51+
}
52+
53+
@Test
54+
public void testAccessTokenFromImpersonatedCredentials()
55+
throws IOException {
56+
AccessTokenFromImpersonatedCredentials.getAccessToken(impersonatedServiceAccount, scope);
57+
String output = bout.toString();
58+
assertTrue(output.contains("Generated access token."));
59+
}
60+
61+
@After
62+
public void tearDown() throws IOException {
63+
System.setOut(originalOut);
64+
bout.reset();
65+
}
66+
}

0 commit comments

Comments
 (0)