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_explicit_adc] 18 19 import com.google.api.gax.paging.Page; 20 import com.google.auth.oauth2.GoogleCredentials; 21 import com.google.cloud.storage.Bucket; 22 import com.google.cloud.storage.Storage; 23 import com.google.cloud.storage.StorageOptions; 24 import java.io.IOException; 25 import java.security.GeneralSecurityException; 26 27 public class AuthenticateExplicit { 28 main(String[] args)29 public static void main(String[] args) throws IOException, GeneralSecurityException { 30 // TODO(Developer): 31 // 1. Replace the project variable below. 32 // 2. Make sure you have the necessary permission to list storage buckets 33 // "storage.buckets.list" 34 35 String projectId = "your-google-cloud-project-id"; 36 37 authenticateExplicit(projectId); 38 } 39 40 // List storage buckets by authenticating with ADC. authenticateExplicit(String projectId)41 public static void authenticateExplicit(String projectId) throws IOException { 42 // Construct the GoogleCredentials object which obtains the default configuration from your 43 // working environment. 44 // GoogleCredentials.getApplicationDefault() will give you ComputeEngineCredentials 45 // if you are on a GCE (or other metadata server supported environments). 46 GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); 47 // If you are authenticating to a Cloud API, you can let the library include the default scope, 48 // https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained 49 // permissions for Cloud. 50 // If you need to provide a scope, specify it as follows: 51 // GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() 52 // .createScoped(scope); 53 // For more information on scopes to use, 54 // see: https://developers.google.com/identity/protocols/oauth2/scopes 55 56 // Construct the Storage client. 57 Storage storage = 58 StorageOptions.newBuilder() 59 .setCredentials(credentials) 60 .setProjectId(projectId) 61 .build() 62 .getService(); 63 64 System.out.println("Buckets:"); 65 Page<Bucket> buckets = storage.list(); 66 for (Bucket bucket : buckets.iterateAll()) { 67 System.out.println(bucket.toString()); 68 } 69 System.out.println("Listed all storage buckets."); 70 } 71 } 72 // [END auth_cloud_explicit_adc] 73