Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
69047a6
docs(samples): add auth samples and tests (#1102)
Sita04 Aug 23, 2022
4520622
chore(deps): update dependency google-cloud-compute to v1.5.1 (#1110)
renovate-bot Aug 23, 2022
f0e2295
chore(deps): update dependency google-auth to v2.11.0 (#1109)
renovate-bot Aug 23, 2022
8632a2f
chore(deps): update dependency google-cloud-storage to v2.5.0 (#1111)
renovate-bot Aug 23, 2022
241d57c
fix: don't retry if error or error_description is not string (#1241)
arithmetic1728 Mar 1, 2023
7a0e5b2
fix: misc fixes (#1316)
arithmetic1728 Jun 1, 2023
4726bf3
feat: Add support for Python 3.12 (#1421)
parthea Nov 29, 2023
ea361dd
fix: explicitly declare support for Python 3.13 (#1741)
parthea Apr 10, 2025
9740b8a
doc: Custom Credential Suppliers for AWS and Okta. (#1830)
vverman Nov 11, 2025
428f069
feat: support Python 3.14 (#1822)
Linchin Dec 12, 2025
5c94b2f
chore(deps): update dependency requests to v2.32.4 [security] (#1871)
renovate-bot Dec 17, 2025
6a756d3
chore(deps): update all dependencies (#1894)
renovate-bot Jan 5, 2026
7c526b6
chore(deps): update all dependencies (#1923)
renovate-bot Jan 12, 2026
d32ccf6
chore(deps): update dependency google-cloud-storage to v3.8.0 (#1935)
renovate-bot Jan 14, 2026
e13fe12
chore(deps): update dependency google-cloud-compute to v1.42.0 (#1939)
renovate-bot Jan 15, 2026
e7ffb3a
Merge remote-tracking branch 'migration/main' into google-auth-librar…
chalmerlowe Feb 5, 2026
e1f3c20
updates import order and adds annotation authenticate_explicit_with_a…
chalmerlowe Feb 6, 2026
02495c1
adds annotations authenticate_implicit_with_adc.py
chalmerlowe Feb 6, 2026
1bf2889
reorders imports and adds annotations custom_aws_supplier.py
chalmerlowe Feb 6, 2026
bc0bd22
reorders imports and adds annotations custom_okta_supplier.py
chalmerlowe Feb 6, 2026
2cb2c54
adds annotation idtoken_from_impersonated_credentials.py
chalmerlowe Feb 6, 2026
0e7985e
reorders imports and adds annotation idtoken_from_metadata_server.py
chalmerlowe Feb 6, 2026
1d3e12a
adds annotation idtoken_from_service_account.py
chalmerlowe Feb 6, 2026
93f1fa5
reorders imports and adds annotation snippets_test.py
chalmerlowe Feb 6, 2026
b01858f
adds annotations verify_google_idtoken.py
chalmerlowe Feb 6, 2026
b43e189
updates import order authenticate_explicit_with_adc.py
chalmerlowe Feb 6, 2026
23a2b62
updates import order custom_okta_supplier.py
chalmerlowe Feb 6, 2026
6476516
updates line spacing
chalmerlowe Feb 6, 2026
af4fdbb
reorders import custom_okta_supplier.py
chalmerlowe Feb 6, 2026
fe76537
Apply suggestion from @gemini-code-assist[bot]
chalmerlowe Feb 6, 2026
68e5bad
Update licence to reflect Google LLC
chalmerlowe Feb 6, 2026
e816abf
updates credential demo to mask the access_key
chalmerlowe Feb 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions auth/cloud-client-temp/authenticate_explicit_with_adc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright 2022 Google LLC
#
# 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.

# [START auth_cloud_explicit_adc]


import google.auth
from google.cloud import storage
import google.oauth2.credentials


def authenticate_explicit_with_adc() -> None:
"""
List storage buckets by authenticating with ADC.

// TODO(Developer):
// 1. Before running this sample,
// set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
// 2. Replace the project variable.
// 3. Make sure you have the necessary permission to list storage buckets: "storage.buckets.list"
"""

# Construct the Google credentials object which obtains the default configuration from your
# working environment.
# google.auth.default() will give you ComputeEngineCredentials
# if you are on a GCE (or other metadata server supported environments).
credentials, project_id = google.auth.default()
# If you are authenticating to a Cloud API, you can let the library include the default scope,
# https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained
# permissions for Cloud.
# If you need to provide a scope, specify it as follows:
# credentials = google.auth.default(scopes=scope)
# For more information on scopes to use,
# see: https://developers.google.com/identity/protocols/oauth2/scopes

# Construct the Storage client.
storage_client = storage.Client(credentials=credentials, project=project_id)
buckets = storage_client.list_buckets()
print("Buckets:")
for bucket in buckets:
print(bucket.name)
print("Listed all storage buckets.")

# [END auth_cloud_explicit_adc]
46 changes: 46 additions & 0 deletions auth/cloud-client-temp/authenticate_implicit_with_adc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright 2022 Google LLC
#
# 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.

# [START auth_cloud_implicit_adc]

from google.cloud import storage


def authenticate_implicit_with_adc(project_id: str = "your-google-cloud-project-id") -> None:
"""
When interacting with Google Cloud Client libraries, the library can auto-detect the
credentials to use.

// TODO(Developer):
// 1. Before running this sample,
// set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
// 2. Replace the project variable.
// 3. Make sure that the user account or service account that you are using
// has the required permissions. For this sample, you must have "storage.buckets.list".
Args:
project_id: The project id of your Google Cloud project.
"""

# This snippet demonstrates how to list buckets.
# *NOTE*: Replace the client created below with the client required for your application.
# Note that the credentials are not specified when constructing the client.
# Hence, the client library will look for credentials using ADC.
storage_client = storage.Client(project=project_id)
buckets = storage_client.list_buckets()
print("Buckets:")
for bucket in buckets:
print(bucket.name)
print("Listed all storage buckets.")

# [END auth_cloud_implicit_adc]
119 changes: 119 additions & 0 deletions auth/cloud-client-temp/custom_aws_supplier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Copyright 2025 Google LLC
# 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 json
import os
import sys

import boto3
from dotenv import load_dotenv
from google.auth.aws import AwsSecurityCredentials, AwsSecurityCredentialsSupplier
from google.auth.aws import Credentials as AwsCredentials
from google.auth.exceptions import GoogleAuthError
from google.auth.transport.requests import AuthorizedSession

load_dotenv()


class CustomAwsSupplier(AwsSecurityCredentialsSupplier):
"""Custom AWS Security Credentials Supplier."""

def __init__(self) -> None:
"""Initializes the Boto3 session, prioritizing environment variables for region."""
# Explicitly read the region from the environment first. This ensures that
# a value from a .env file is picked up reliably for local testing.
region = os.getenv("AWS_REGION") or os.getenv("AWS_DEFAULT_REGION")

# If region is None, Boto3's discovery chain will be used when needed.
self.session = boto3.Session(region_name=region)
self._cached_region = None
print(f"[INFO] CustomAwsSupplier initialized. Region from env: {region}")

def get_aws_region(self, context: object, request: object) -> str:
"""Returns the AWS region using Boto3's default provider chain."""
if self._cached_region:
return self._cached_region

# Accessing region_name will use the value from the constructor if provided,
# otherwise it triggers Boto3's lazy-loading discovery (e.g., metadata service).
self._cached_region = self.session.region_name

if not self._cached_region:
print("[ERROR] Boto3 was unable to resolve an AWS region.", file=sys.stderr)
raise GoogleAuthError("Boto3 was unable to resolve an AWS region.")

print(f"[INFO] Boto3 resolved AWS Region: {self._cached_region}")
return self._cached_region

def get_aws_security_credentials(self, context: object, request: object = None) -> AwsSecurityCredentials:
"""Retrieves AWS security credentials using Boto3's default provider chain."""
aws_credentials = self.session.get_credentials()
if not aws_credentials:
print("[ERROR] Unable to resolve AWS credentials.", file=sys.stderr)
raise GoogleAuthError("Unable to resolve AWS credentials from the provider chain.")

# Instead of printing the whole key, mask everything but the last 4 characters
masked_access_key = f"{'*' * 16}{aws_credentials.access_key[-4:]}"
print(f"[INFO] Resolved AWS Access Key ID: {masked_access_key}")

return AwsSecurityCredentials(
access_key_id=aws_credentials.access_key,
secret_access_key=aws_credentials.secret_key,
session_token=aws_credentials.token,
)


def main() -> None:
"""Main function to demonstrate the custom AWS supplier."""
print("--- Starting Script ---")

gcp_audience = os.getenv("GCP_WORKLOAD_AUDIENCE")
sa_impersonation_url = os.getenv("GCP_SERVICE_ACCOUNT_IMPERSONATION_URL")
gcs_bucket_name = os.getenv("GCS_BUCKET_NAME")

print(f"GCP_WORKLOAD_AUDIENCE: {gcp_audience}")
print(f"GCS_BUCKET_NAME: {gcs_bucket_name}")

if not all([gcp_audience, sa_impersonation_url, gcs_bucket_name]):
print("[ERROR] Missing required environment variables.", file=sys.stderr)
raise GoogleAuthError("Missing required environment variables.")

custom_supplier = CustomAwsSupplier()

credentials = AwsCredentials(
audience=gcp_audience,
subject_token_type="urn:ietf:params:aws:token-type:aws4_request",
service_account_impersonation_url=sa_impersonation_url,
aws_security_credentials_supplier=custom_supplier,
scopes=['https://www.googleapis.com/auth/devstorage.read_write'],
)

bucket_url = f"https://storage.googleapis.com/storage/v1/b/{gcs_bucket_name}"
print(f"Request URL: {bucket_url}")

authed_session = AuthorizedSession(credentials)
try:
print("Attempting to make authenticated request to Google Cloud Storage...")
res = authed_session.get(bucket_url)
res.raise_for_status()
print("\n--- SUCCESS! ---")
print("Successfully authenticated and retrieved bucket data:")
print(json.dumps(res.json(), indent=2))
except Exception as e:
print("--- FAILED --- ", file=sys.stderr)
print(e, file=sys.stderr)
exit(1)


if __name__ == "__main__":
main()
Loading