1919
2020from google .oauth2 .service_account import Credentials as ServiceAccountCreds
2121from google .oauth2 .credentials import Credentials as InstalledAppCredentials
22+ from google .auth import default as ApplicationDefaultCredentials
23+ from google .auth .credentials import Credentials as CredentialsBaseClass
2224from google .auth .transport .requests import Request
2325
2426from google .ads .googleads import config
@@ -109,9 +111,23 @@ def get_service_account_credentials(
109111 )
110112
111113
112- def get_credentials (
113- config_data : dict [str , Any ]
114- ) -> Union [InstalledAppCredentials , ServiceAccountCreds ]:
114+ @_initialize_credentials_decorator
115+ def get_application_default_credentials (
116+ scopes : list [str ] = _SERVICE_ACCOUNT_SCOPES
117+ ) -> CredentialsBaseClass :
118+ """Loads Application Default Credentials as returns them.
119+
120+ Args:
121+ scopes: A list of additional scopes.
122+
123+ Returns:
124+ An instance of auth.credentials.Credentials
125+ """
126+ (credentials , _ ) = ApplicationDefaultCredentials (scopes = scopes )
127+ return credentials
128+
129+
130+ def get_credentials (config_data : dict [str , Any ]) -> CredentialsBaseClass :
115131 """Decides which type of credentials to return based on the given config.
116132
117133 Args:
@@ -127,20 +143,23 @@ def get_credentials(
127143 str , ...
128144 ] = config .get_oauth2_required_service_account_keys ()
129145
146+ if config_data .get ("use_application_default_credentials" ):
147+ # Using Application Default Credentials
148+ return get_application_default_credentials ()
130149 if all (key in config_data for key in required_installed_app_keys ):
131150 # Using the Installed App Flow
132151 return get_installed_app_credentials (
133- config_data .get ("client_id" ), # type: ignore[arg-type]
134- config_data .get ("client_secret" ), # type: ignore[arg-type]
135- config_data .get ("refresh_token" ), # type: ignore[arg-type]
136- http_proxy = config_data .get ("http_proxy" ), # type: ignore[arg-type]
152+ config_data .get ("client_id" ),
153+ config_data .get ("client_secret" ),
154+ config_data .get ("refresh_token" ),
155+ http_proxy = config_data .get ("http_proxy" ),
137156 )
138157 elif all (key in config_data for key in required_service_account_keys ):
139158 # Using the Service Account Flow
140159 return get_service_account_credentials (
141- config_data .get ("json_key_file_path" ), # type: ignore[arg-type]
142- config_data .get ("impersonated_email" ), # type: ignore[arg-type]
143- http_proxy = config_data .get ("http_proxy" ), # type: ignore[arg-type]
160+ config_data .get ("json_key_file_path" ),
161+ config_data .get ("impersonated_email" ),
162+ http_proxy = config_data .get ("http_proxy" ),
144163 )
145164 else :
146165 raise ValueError (
0 commit comments