• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google Inc.
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_implicit_adc]
18 
19 import com.google.api.gax.paging.Page;
20 import com.google.cloud.storage.Bucket;
21 import com.google.cloud.storage.Storage;
22 import com.google.cloud.storage.StorageOptions;
23 import java.io.IOException;
24 
25 public class AuthenticateImplicitWithAdc {
26 
main(String[] args)27   public static void main(String[] args) throws IOException {
28     // TODO(Developer):
29     //  1. Before running this sample,
30     //  set up Application Default Credentials as described in
31     //  https://cloud.google.com/docs/authentication/external/set-up-adc
32     //  2. Replace the project variable below.
33     //  3. Make sure you have the necessary permission to list storage buckets
34     //  "storage.buckets.list"
35     String projectId = "your-google-cloud-project-id";
36     authenticateImplicitWithAdc(projectId);
37   }
38 
39   // When interacting with Google Cloud Client libraries, the library can auto-detect the
40   // credentials to use.
authenticateImplicitWithAdc(String project)41   public static void authenticateImplicitWithAdc(String project) throws IOException {
42 
43     // *NOTE*: Replace the client created below with the client required for your application.
44     // Note that the credentials are not specified when constructing the client.
45     // Hence, the client library will look for credentials using ADC.
46     //
47     // Initialize client that will be used to send requests. This client only needs to be created
48     // once, and can be reused for multiple requests.
49     Storage storage = StorageOptions.newBuilder().setProjectId(project).build().getService();
50 
51     System.out.println("Buckets:");
52     Page<Bucket> buckets = storage.list();
53     for (Bucket bucket : buckets.iterateAll()) {
54       System.out.println(bucket.toString());
55     }
56     System.out.println("Listed all storage buckets.");
57   }
58 }
59 // [END auth_cloud_implicit_adc]
60