Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(samples): added auth samples and tests #927

Merged
merged 30 commits into from Aug 4, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3bd604d
docs(samples): added client code for idtoken, adc and metadata server
Sita04 Jun 6, 2022
bd1bc55
docs(samples): added authexplicit and copyright
Sita04 Jun 8, 2022
ece1c56
docs(samples): add auth with metadata server
Sita04 Jun 8, 2022
0c26c33
docs(samples): minor refactoring and added tests
Sita04 Jun 8, 2022
45449b2
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jun 8, 2022
7ef36df
Merge branch 'main' into auth-samples
Shabirmean Jun 14, 2022
b2f367e
refactored acc to review comments
Sita04 Jul 18, 2022
01b57ad
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Jul 18, 2022
b9dee60
Merge branch 'main' into auth-samples
Sita04 Jul 18, 2022
3ed6be0
refactored acc to review comments
Sita04 Jul 22, 2022
dd39fd4
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Jul 22, 2022
a46ccc4
Merge branch 'main' into auth-samples
Sita04 Jul 25, 2022
5eb6506
refactored acc to review comments
Sita04 Jul 28, 2022
cc6a5a5
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Jul 28, 2022
7c68634
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jul 28, 2022
1baeebe
minor comment update
Sita04 Jul 28, 2022
9fc3a7a
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Jul 28, 2022
b8c5f3f
Merge branch 'main' into auth-samples
Sita04 Jul 29, 2022
680cfdd
modified google id token verification and removed third party dependency
Sita04 Jul 29, 2022
1944e5d
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Jul 29, 2022
a943290
removed third party deps from pom
Sita04 Jul 29, 2022
d7d6257
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jul 29, 2022
cf11754
Merge branch 'auth-samples' of https://github.com/googleapis/google-a…
gcf-owl-bot[bot] Jul 29, 2022
b910be5
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jul 29, 2022
e23fe35
Merge branch 'auth-samples' of https://github.com/googleapis/google-a…
gcf-owl-bot[bot] Jul 29, 2022
ada91fb
Merge branch 'main' into auth-samples
Sita04 Jul 29, 2022
8573bb3
Merge branch 'main' into auth-samples
Sita04 Aug 4, 2022
591d0e6
included comment about verifying Google ID tokens
Sita04 Aug 4, 2022
82d7350
Merge remote-tracking branch 'origin/auth-samples' into auth-samples
Sita04 Aug 4, 2022
54013b5
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Aug 4, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
101 changes: 101 additions & 0 deletions samples/snippets/pom.xml
@@ -0,0 +1,101 @@
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.auth.samples</groupId>
<artifactId>authsamples</artifactId>
<version>1.0.0</version>
<name>auth-samples</name>


<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
</parent>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<!-- START dependencies -->
<!-- Using libraries-bom to manage versions.
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>25.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>


<dependencies>
<!-- OAuth dependency-->
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.3.0</version>
</dependency>

<!-- IAM dependency-->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iam</artifactId>
<version>v1-rev20220509-1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iamcredentials</artifactId>
<version>v1-rev20211203-1.32.1</version>
</dependency>

<!-- JWT dependency-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.16.0</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.18.0</version>
</dependency>

<!-- GCloud dependency-->
<dependency>
<artifactId>google-cloud-compute</artifactId>
<groupId>com.google.cloud</groupId>
<version>1.8.1</version>
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
</dependency>

<!-- Test dependencies-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<artifactId>truth</artifactId>
<groupId>com.google.truth</groupId>
<scope>test</scope>
<version>1.1.3</version>
</dependency>

</dependencies>

</project>

@@ -0,0 +1,79 @@
/*
* 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.
*/

import com.google.api.gax.paging.Page;
import com.google.auth.oauth2.ComputeEngineCredentials;
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 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"
String projectId = "your-google-cloud-project-id";

authWithCredentialsFromMetadataServer(projectId);
}

// Authenticating using Client libraries can be done in one of the following ways:
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// 1. Implicit authentication with ADC (Application Default Credentials)
// 2. Explicit authentication by specifying the service account
// 3. Authentication with service account credentials obtained from a metadata server, like,
// Compute Engine or App Engine etc.,
// 4. Bring your own (BYO) access token
// 5. Using API keys (for libraries that support)
//
// In this snippet, we demonstrate "Authentication with service account credentials
// obtained from a metadata server".
public static void authWithCredentialsFromMetadataServer(String project) {

// This snippet demonstrates how to initialize Cloud Storage and list buckets.
// Note that the credentials are requested from the ComputeEngine metadata server.
Storage storage = initService(project);
Sita04 marked this conversation as resolved.
Show resolved Hide resolved

System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
System.out.println("Authentication complete.");
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
}

// Initialize the Storage client by getting the Service account credentials
// from a Metadata server.
private static Storage initService(String projectId) {
// Explicitly request the service account credentials from the ComputeEngine metadata server.
GoogleCredentials credentials = ComputeEngineCredentials.create();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the past, we haven't wanted to encourage folks to explicitly pick the credential type -- the code won't work on other environments (like development).

GoogleCredentials.getApplicationDefault() will give you ComputeEngineCredentials if you are on a GCE (or other metadata server supported environments).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 to ADC. Can we also demonstrate how the user specifies a scope?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree.. modified to use ADC and also added a comment.

@kurtisvg we didn't want to demonstrate scopes as we thought it had a limited usecase for GCP and primarily only workspace products need it. @piaxc can you weigh in on the "scopes" part?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To chingor13@'s comment: the idea here was to specifically get credentials from the Metadata server. This is in keeping with previous samples that have been provided, although this sample won't be included in the docs. Sita04@, how will this differ from the implicit flow now? Maybe we could just remove it?

kurtisvg@: for Cloud APIs, the best practice as communicated by the IAM team is to use the cloud-wide scope "https://www.googleapis.com/auth/cloud-platform" and use IAM only to restrict access. That is the guidance I'm providing in the Authentication documentation. Maybe we could provide more color?

For Cloud APIs, you can let the library use the default scope of https://www.googleapis.com/auth/cloud-platform because IAM provides fine-grained access control.

Or something like that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's best to remove the sample as there is very minute difference between this one and the ADC explicit.
I'll add an extra comment in that sample that @chingor13 mentioned "GoogleCredentials.getApplicationDefault() will give you ComputeEngineCredentials if you are on a GCE (or other metadata server supported environments)." ?


// Alternately, if executing within AppEngine, you can get credentials as follows:
// GoogleCredentials credentials = AppEngineCredentials.getApplicationDefault();

// Construct the Storage client.
// Note that, here we explicitly specify the service account to use.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
return StorageOptions.newBuilder()
.setCredentials(credentials)
.setProjectId(projectId)
.build()
.getService();
}
}
89 changes: 89 additions & 0 deletions samples/snippets/src/main/java/AuthenticateExplicit.java
@@ -0,0 +1,89 @@
/*
* 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.
*/

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 com.google.common.collect.Lists;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class AuthenticateExplicit {
Sita04 marked this conversation as resolved.
Show resolved Hide resolved

public static void main(String[] args) throws IOException, GeneralSecurityException {
// TODO(Developer):
// 1. Replace the below variable.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// 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.
String jsonCredentialPath = "path-to-json-credential-file";

// Provide the scopes that you might need to request to access Google APIs,
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// depending on the level of access you need.
// Example: The following scope lets you view and manage Pub/Sub topics and subscriptions.
// For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes
String scope = "https://www.googleapis.com/auth/devstorage.full_control";
Sita04 marked this conversation as resolved.
Show resolved Hide resolved

authenticateExplicit(projectId, jsonCredentialPath, scope);
}

// Authenticating using Client libraries can be done in one of the following ways:
// 1. Implicit authentication with ADC (Application Default Credentials)
// 2. Explicit authentication by specifying the service account
// 3. Authentication with service account credentials obtained from metadata server, like,
// Compute Engine or App Engine etc.,
// 4. Bring your own (BYO) access token
// 5. Using API keys (for libraries that support)
//
// In this snippet, we demonstrate "Explicit authentication by specifying the service account".
public static void authenticateExplicit(String project, String jsonCredentialPath, String scope)
throws IOException {

// This snippet demonstrates how to initialize Cloud Storage and list buckets.
// Note that the credentials are explicitly specified when constructing the client.
Storage storage = initService(project, jsonCredentialPath, scope);

System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
System.out.println("Authentication complete.");
}

// Initialize the Storage client by explicitly setting the Service account to use.
private static Storage initService(String projectId, String jsonCredentialPath, String scope)
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));

// Construct the Storage client.
// Note that, here we explicitly specify the service account to use.
return StorageOptions.newBuilder()
.setCredentials(credentials)
.setProjectId(projectId)
.build()
.getService();
}
}
80 changes: 80 additions & 0 deletions samples/snippets/src/main/java/AuthenticateImplicitWithAdc.java
@@ -0,0 +1,80 @@
/*
* 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.
*/

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):
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// 1. Set the following environment variable before running the code.
// APPLICATION_DEFAULT_CREDENTIALS="path-to-the-service-account-json-credential-file"
// 2. Replace the below variable.
// 3. Make sure you have the necessary permission "compute.instances.list"
String projectId = "your-google-cloud-project-id";
authenticateImplicitWithAdc(projectId);
}

// Authenticating using Client libraries can be done in one of the following ways:
// 1. Implicit authentication with ADC (Application Default Credentials)
// 2. Explicit authentication by specifying the service account
// 3. Authentication with service account credentials obtained from metadata server, like,
// Compute Engine or App Engine etc.,
// 4. Bring your own (BYO) access token
// 5. Using API keys (for libraries that support)
//
// In this snippet, we demonstrate "Implicit authentication with ADC".
// ADC - Application Default Credentials
// When interacting with Google Cloud Client libraries, the library can auto-detect the
// credentials to use, if the "APPLICATION_DEFAULT_CREDENTIALS" is set.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// This APPLICATION_DEFAULT_CREDENTIALS is an environment variable/ configuration.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// This configuration can be made available to the code in various ways depending upon where the
// code is executed.
// Examples:
// 1. If running your code in local development environment, just set the following environment
// variable:
// APPLICATION_DEFAULT_CREDENTIALS="path-to-the-service-account-json-file" OR
// You can also set the ADC with gcloud if you have the gcloud installed:
// gcloud auth application-default login
//
// 2. When you use a Google Cloud cloud-based development environment such as Cloud Shell or
// 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
//
// ADC detection is independent of the client library and language and works with all Cloud Client
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// libraries.
public static void authenticateImplicitWithAdc(String project) throws IOException {

String zone = "us-central1-a";
// This snippet demonstrates how to initialize Cloud Compute Engine and list instances.
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// Note that the credentials are not specified when constructing the client.
// Hence, the client library will look for credentials via the
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// environment variable GOOGLE_APPLICATION_CREDENTIALS.
try (InstancesClient instancesClient = InstancesClient.create()) {
Sita04 marked this conversation as resolved.
Show resolved Hide resolved
// 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 #######");
}
}
}