|
| 1 | +# Copyright 2022 Google Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START auth_cloud_explicit_adc] |
| 16 | + |
| 17 | +from google.cloud import storage |
| 18 | + |
| 19 | +import google.oauth2.credentials |
| 20 | +import google.auth |
| 21 | + |
| 22 | + |
| 23 | +def authenticate_explicit_with_adc(): |
| 24 | + """ |
| 25 | + List storage buckets by authenticating with ADC. |
| 26 | +
|
| 27 | + // TODO(Developer): |
| 28 | + // 1. Before running this sample, |
| 29 | + // set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc |
| 30 | + // 2. Replace the project variable. |
| 31 | + // 3. Make sure you have the necessary permission to list storage buckets: "storage.buckets.list" |
| 32 | + """ |
| 33 | + |
| 34 | + # Construct the Google credentials object which obtains the default configuration from your |
| 35 | + # working environment. |
| 36 | + # google.auth.default() will give you ComputeEngineCredentials |
| 37 | + # if you are on a GCE (or other metadata server supported environments). |
| 38 | + credentials, project_id = google.auth.default() |
| 39 | + # If you are authenticating to a Cloud API, you can let the library include the default scope, |
| 40 | + # https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained |
| 41 | + # permissions for Cloud. |
| 42 | + # If you need to provide a scope, specify it as follows: |
| 43 | + # credentials = google.auth.default(scopes=scope) |
| 44 | + # For more information on scopes to use, |
| 45 | + # see: https://developers.google.com/identity/protocols/oauth2/scopes |
| 46 | + |
| 47 | + # Construct the Storage client. |
| 48 | + storage_client = storage.Client(credentials=credentials, project=project_id) |
| 49 | + buckets = storage_client.list_buckets() |
| 50 | + print("Buckets:") |
| 51 | + for bucket in buckets: |
| 52 | + print(bucket.name) |
| 53 | + print("Listed all storage buckets.") |
| 54 | + |
| 55 | +# [END auth_cloud_explicit_adc] |
0 commit comments