Skip to content

Commit

Permalink
🦉 Updates from OwlBot post-processor
Browse files Browse the repository at this point in the history
  • Loading branch information
gcf-owl-bot[bot] committed Jun 8, 2022
1 parent 0c26c33 commit 45449b2
Show file tree
Hide file tree
Showing 10 changed files with 150 additions and 143 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public class AuthWithCredentialsFromMetadataServer {
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer):
// 1. Replace the below variable.
// 2. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
// 2. Make sure you have the necessary permission to list storage buckets
// "storage.buckets.list"
String projectId = "your-google-cloud-project-id";

authWithCredentialsFromMetadataServer(projectId);
Expand Down
9 changes: 5 additions & 4 deletions samples/snippets/src/main/java/AuthenticateExplicit.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public class AuthenticateExplicit {
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer):
// 1. Replace the below variable.
// 2. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
// 2. Make sure you have the necessary permission to list storage buckets
// "storage.buckets.list"
String projectId = "your-google-cloud-project-id";

// Path to the service account json credential file.
Expand Down Expand Up @@ -73,9 +74,9 @@ private static Storage initService(String projectId, String jsonCredentialPath,
throws IOException {
// Construct the GoogleCredentials object which accepts the service account json file and
// scope as the input parameters.
GoogleCredentials credentials = GoogleCredentials
.fromStream(new FileInputStream(jsonCredentialPath))
.createScoped(Lists.newArrayList(scope));
GoogleCredentials credentials =
GoogleCredentials.fromStream(new FileInputStream(jsonCredentialPath))
.createScoped(Lists.newArrayList(scope));

// Construct the Storage client.
// Note that, here we explicitly specify the service account to use.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ public static void main(String[] args) throws IOException {
// Cloud Code, the tool uses the credentials you provided when you logged in,
// and manages any authorizations required.
//
// For more environments, see: https://cloud.devsite.corp.google.com/docs/authentication/provide-credentials-adc
// For more environments, see:
// https://cloud.devsite.corp.google.com/docs/authentication/provide-credentials-adc
//
// ADC detection is independent of the client library and language and works with all Cloud Client
// libraries.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@

public class IdTokenFromImpersonatedCredentials {

public static void main(String[] args)
throws IOException, GeneralSecurityException {
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer): Replace the below variables before running the code.

// Your Google Cloud project id.
Expand All @@ -54,15 +53,17 @@ public static void main(String[] args)
String targetAudience = "pubsub.googleapis.com";

// The service account name of the limited-privilege account for whom the credential is created.
String impersonatedServiceAccount =
"name@project.service.gserviceaccount.com";
String impersonatedServiceAccount = "name@project.service.gserviceaccount.com";

getIdTokenFromImpersonatedCredentials(projectId, jsonCredentialPath, impersonatedServiceAccount,
scope, targetAudience);
getIdTokenFromImpersonatedCredentials(
projectId, jsonCredentialPath, impersonatedServiceAccount, scope, targetAudience);
}

public static void getIdTokenFromImpersonatedCredentials(String projectId,
String jsonCredentialPath, String impersonatedServiceAccount, String scope,
public static void getIdTokenFromImpersonatedCredentials(
String projectId,
String jsonCredentialPath,
String impersonatedServiceAccount,
String scope,
String targetAudience)
throws GeneralSecurityException, IOException {

Expand All @@ -87,20 +88,23 @@ public static void getIdTokenFromImpersonatedCredentials(String projectId,
List<String> delegates = null;

// Set the target audience and Token options.
GenerateIdTokenRequest idTokenRequest = new GenerateIdTokenRequest()
.setAudience(targetAudience)
.setDelegates(delegates)
// Setting this will include email in the id token.
.setIncludeEmail(Boolean.TRUE);
GenerateIdTokenRequest idTokenRequest =
new GenerateIdTokenRequest()
.setAudience(targetAudience)
.setDelegates(delegates)
// Setting this will include email in the id token.
.setIncludeEmail(Boolean.TRUE);

// Generate the id token for the impersonated service account, using the generateIdToken()
// from IAMCredentials class.
GenerateIdToken idToken = service
.projects()
.serviceAccounts()
.generateIdToken(
String.format("projects/%s/serviceAccounts/%s", projectId, impersonatedServiceAccount),
idTokenRequest);
GenerateIdToken idToken =
service
.projects()
.serviceAccounts()
.generateIdToken(
String.format(
"projects/%s/serviceAccounts/%s", projectId, impersonatedServiceAccount),
idTokenRequest);

// Verify the obtained id token. This is done at the receiving end of the OIDC endpoint.
boolean isVerified = verifyGoogleIdToken(idToken.getAccessToken(), targetAudience);
Expand All @@ -119,9 +123,9 @@ private static IAMCredentials initService(String jsonCredentialPath, String scop

// Initialize the IAMCredentials service.
return new IAMCredentials.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
}
Expand All @@ -130,10 +134,11 @@ private static IAMCredentials initService(String jsonCredentialPath, String scop
private static boolean verifyGoogleIdToken(String idTokenString, String audience)
throws GeneralSecurityException, IOException {
// Initialize the Google id token verifier and set the audience.
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();

// Verify the id token.
GoogleIdToken idToken = verifier.verify(idTokenString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@

public class IdTokenFromImpersonatedCredentialsREST {

public static void main(String[] args)
throws IOException, GeneralSecurityException {
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer): Replace the below variables before running the code.
// Path to the service account json credential file.
String jsonCredentialPath = "path-to-json-credential-file";
Expand All @@ -55,27 +54,31 @@ public static void main(String[] args)
String targetAudience = "pubsub.googleapis.com";

// The service account name of the limited-privilege account for whom the credential is created.
String impersonatedServiceAccount =
"name@project.service.gserviceaccount.com";
String impersonatedServiceAccount = "name@project.service.gserviceaccount.com";

getIdTokenFromImpersonatedCredentials(jsonCredentialPath, impersonatedServiceAccount, scope,
targetAudience);
getIdTokenFromImpersonatedCredentials(
jsonCredentialPath, 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 getIdTokenFromImpersonatedCredentials(String jsonCredentialPath,
String impersonatedServiceAccount, String scope,
String targetAudience) throws IOException, GeneralSecurityException {
public static void getIdTokenFromImpersonatedCredentials(
String jsonCredentialPath,
String impersonatedServiceAccount,
String scope,
String targetAudience)
throws IOException, GeneralSecurityException {
// Initialize the Service Account Credentials class with the path to the json file.
// The caller who issues a request for the short-lived credentials.
ServiceAccountCredentials serviceAccountCredentials = ServiceAccountCredentials.fromStream(
new FileInputStream(jsonCredentialPath));
ServiceAccountCredentials serviceAccountCredentials =
ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialPath));
// Restrict the scope of the service account.
serviceAccountCredentials = (ServiceAccountCredentials) serviceAccountCredentials.createScoped(
Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
serviceAccountCredentials =
(ServiceAccountCredentials)
serviceAccountCredentials.createScoped(
Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));

// delegates: The chained list of delegates required to grant the final accessToken.
//
Expand All @@ -89,20 +92,22 @@ public static void getIdTokenFromImpersonatedCredentials(String jsonCredentialPa
List<String> delegates = null;

// Create the impersonated credential.
ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create(
serviceAccountCredentials,
impersonatedServiceAccount,
delegates,
Arrays.asList(scope),
300);
ImpersonatedCredentials impersonatedCredentials =
ImpersonatedCredentials.create(
serviceAccountCredentials,
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();
IdTokenCredentials idTokenCredentials =
IdTokenCredentials.newBuilder()
.setIdTokenProvider(impersonatedCredentials)
.setTargetAudience(targetAudience)
// Setting this will include email in the id token.
.setOptions(Arrays.asList(Option.INCLUDE_EMAIL))
.build();

// Make a http request with the idTokenCredentials to obtain the access token.
// stsEndpoint: The Security Token Service exchanges Google or third-party credentials for a
Expand All @@ -112,8 +117,8 @@ public static void getIdTokenFromImpersonatedCredentials(String jsonCredentialPa
makeAuthenticatedRequest(idTokenCredentials, stsEndpoint);

// Verify the obtained id token. This is done at the receiving end of the OIDC endpoint.
boolean isVerified = verifyGoogleIdToken(idTokenCredentials.getAccessToken().getTokenValue(),
targetAudience);
boolean isVerified =
verifyGoogleIdToken(idTokenCredentials.getAccessToken().getTokenValue(), targetAudience);
if (isVerified) {
System.out.println("Id token verified.");
return;
Expand All @@ -137,10 +142,11 @@ private static void makeAuthenticatedRequest(IdTokenCredentials idTokenCredentia
private static boolean verifyGoogleIdToken(String idTokenString, String audience)
throws GeneralSecurityException, IOException {
// Initialize the Google id token verifier and set the audience.
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();

// Verify the id token.
GoogleIdToken idToken = verifier.verify(idTokenString);
Expand All @@ -158,5 +164,4 @@ private static boolean verifyGoogleIdToken(String idTokenString, String audience
}
return false;
}

}
36 changes: 19 additions & 17 deletions samples/snippets/src/main/java/IdTokenFromMetadataServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@

public class IdTokenFromMetadataServer {

public static void main(String[] args)
throws IOException, GeneralSecurityException {
public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer): Replace the below variables before running the code.

// The service name for which the id token is requested. Service name refers to the
Expand All @@ -53,20 +52,23 @@ public static void main(String[] args)
// ComputeEngine and use that information to obtain an id token.
// Appengine 2nd Generation, Cloud Run or even Kubernetes engine's also expose a
// metadata server.
// For AppEngine, see: https://cloud.google.com/appengine/docs/standard/java/accessing-instance-metadata#identifying_which_metadata_endpoint_to_use
// For CloudRun container instance, see: https://cloud.google.com/run/docs/container-contract#metadata-server
// For AppEngine, see:
// https://cloud.google.com/appengine/docs/standard/java/accessing-instance-metadata#identifying_which_metadata_endpoint_to_use
// For CloudRun container instance, see:
// https://cloud.google.com/run/docs/container-contract#metadata-server
public static void getIdTokenFromMetadataServer(String targetAudience)
throws GeneralSecurityException, IOException {

// Optionally, you can also set scopes in computeEngineCredentials.
ComputeEngineCredentials computeEngineCredentials = ComputeEngineCredentials.create();

IdTokenCredentials idTokenCredentials = IdTokenCredentials.newBuilder()
.setIdTokenProvider(computeEngineCredentials)
.setTargetAudience(targetAudience)
// Setting the id token options.
.setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE))
.build();
IdTokenCredentials idTokenCredentials =
IdTokenCredentials.newBuilder()
.setIdTokenProvider(computeEngineCredentials)
.setTargetAudience(targetAudience)
// Setting the id token options.
.setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE))
.build();

// Make a http request with the idTokenCredentials to obtain the access token.
// stsEndpoint: The Security Token Service exchanges Google or third-party credentials for a
Expand All @@ -76,8 +78,8 @@ public static void getIdTokenFromMetadataServer(String targetAudience)
makeAuthenticatedRequest(idTokenCredentials, stsEndpoint);

// Verify the obtained id token. This is done at the receiving end of the OIDC endpoint.
boolean isVerified = verifyGoogleIdToken(idTokenCredentials.getAccessToken().getTokenValue(),
targetAudience);
boolean isVerified =
verifyGoogleIdToken(idTokenCredentials.getAccessToken().getTokenValue(), targetAudience);
if (isVerified) {
System.out.println("Id token verified.");
return;
Expand All @@ -101,10 +103,11 @@ private static void makeAuthenticatedRequest(IdTokenCredentials idTokenCredentia
private static boolean verifyGoogleIdToken(String idTokenString, String audience)
throws GeneralSecurityException, IOException {
// Initialize the Google id token verifier and set the audience.
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();

// Verify the id token.
GoogleIdToken idToken = verifier.verify(idTokenString);
Expand All @@ -122,5 +125,4 @@ private static boolean verifyGoogleIdToken(String idTokenString, String audience
}
return false;
}

}
29 changes: 13 additions & 16 deletions samples/snippets/src/main/java/IdTokenFromServiceAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,24 +51,22 @@ public static void main(String[] args)
getIdTokenFromServiceAccount(jsonCredentialPath, scope, targetAudience);
}

public static void getIdTokenFromServiceAccount(String jsonCredentialPath, String scope,
String targetAudience)
public static void getIdTokenFromServiceAccount(
String jsonCredentialPath, String scope, String targetAudience)
throws IOException, GeneralSecurityException {

// Initialize the Service Account Credentials class with the path to the json file.
ServiceAccountCredentials serviceAccountCredentials = ServiceAccountCredentials.fromStream(
new FileInputStream(jsonCredentialPath));
ServiceAccountCredentials serviceAccountCredentials =
ServiceAccountCredentials.fromStream(new FileInputStream(jsonCredentialPath));
// Restrict the scope of the service account.
serviceAccountCredentials = (ServiceAccountCredentials) serviceAccountCredentials.createScoped(
Arrays.asList(scope));
serviceAccountCredentials =
(ServiceAccountCredentials) serviceAccountCredentials.createScoped(Arrays.asList(scope));

// 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<Option> tokenOption = Arrays.asList();
IdToken idToken = serviceAccountCredentials.idTokenWithAudience(
targetAudience,
tokenOption);
IdToken idToken = serviceAccountCredentials.idTokenWithAudience(targetAudience, tokenOption);

// Verify the obtained id token. This is done at the receiving end of the OIDC endpoint.
boolean isVerified = verifyGoogleIdToken(idToken.getTokenValue(), targetAudience);
Expand All @@ -79,15 +77,15 @@ public static void getIdTokenFromServiceAccount(String jsonCredentialPath, Strin
System.out.println("Unable to verify id token.");
}


// Verifies the obtained Google id token.
private static boolean verifyGoogleIdToken(String idTokenString, String audience)
throws GeneralSecurityException, IOException {
// Initialize the Google id token verifier and set the audience.
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(
GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(audience))
.build();

// Verify the id token.
GoogleIdToken idToken = verifier.verify(idTokenString);
Expand All @@ -105,5 +103,4 @@ private static boolean verifyGoogleIdToken(String idTokenString, String audience
}
return false;
}

}
}
Loading

0 comments on commit 45449b2

Please sign in to comment.