diff --git a/google/cloud/alloydb/connector/connector.py b/google/cloud/alloydb/connector/connector.py index 1cd20b1d..8b714263 100644 --- a/google/cloud/alloydb/connector/connector.py +++ b/google/cloud/alloydb/connector/connector.py @@ -23,7 +23,9 @@ from typing import Any, Dict, Optional, Type, TYPE_CHECKING, Union from google.auth import default +from google.auth.credentials import TokenState from google.auth.credentials import with_scopes_if_required +from google.auth.transport import requests from google.cloud.alloydb.connector.client import AlloyDBClient from google.cloud.alloydb.connector.enums import IPTypes @@ -258,6 +260,10 @@ def metadata_exchange( if enable_iam_auth: auth_type = connectorspb.MetadataExchangeRequest.AUTO_IAM + # Ensure the credentials are in fact valid before proceeding. + if not self._credentials.token_state == TokenState.FRESH: + self._credentials.refresh(requests.Request()) + # form metadata exchange request req = connectorspb.MetadataExchangeRequest( user_agent=f"{self._client._user_agent}", # type: ignore