clientViaApplicationDefaultCredentials function

Future<AutoRefreshingAuthClient> clientViaApplicationDefaultCredentials({
  1. required List<String> scopes,
  2. Client? baseClient,
})

Create a client using Application Default Credentials.

Looks for credentials in the following order of preference:

  1. A JSON file whose path is specified by GOOGLE_APPLICATION_CREDENTIALS, this file typically contains exported service account keys.
  2. A JSON file created by gcloud auth application-default login in a well-known location (%APPDATA%/gcloud/application_default_credentials.json on Windows and $HOME/.config/gcloud/application_default_credentials.json on Linux/Mac).
  3. On Google Compute Engine and App Engine Flex we fetch credentials from GCE metadata service.

If baseClient is provided, all HTTP requests will be made with it. Otherwise, a new Client instance will be created.

Implementation

Future<AutoRefreshingAuthClient> clientViaApplicationDefaultCredentials({
  required List<String> scopes,
  Client? baseClient,
}) async {
  if (baseClient == null) {
    baseClient = Client();
  } else {
    baseClient = nonClosingClient(baseClient);
  }

  // If env var specifies a file to load credentials from we'll do that.
  final credsEnv = Platform.environment['GOOGLE_APPLICATION_CREDENTIALS'];
  if (credsEnv != null && credsEnv.isNotEmpty) {
    // If env var is specific and not empty, we always try to load, even if
    // the file doesn't exist.
    return await fromApplicationsCredentialsFile(
      File(credsEnv),
      'GOOGLE_APPLICATION_CREDENTIALS',
      scopes,
      baseClient,
    );
  }

  // Attempt to use file created by `gcloud auth application-default login`
  File credFile;
  if (Platform.isWindows) {
    credFile = File.fromUri(
      Uri.directory(Platform.environment['APPDATA']!)
          .resolve('gcloud/application_default_credentials.json'),
    );
  } else {
    final homeVar = Platform.environment['HOME'];
    if (homeVar == null) {
      throw StateError('The expected environment variable HOME must be set.');
    }
    credFile = File.fromUri(
      Uri.directory(homeVar)
          .resolve('.config/gcloud/application_default_credentials.json'),
    );
  }
  // Only try to load from credFile if it exists.
  if (await credFile.exists()) {
    return await fromApplicationsCredentialsFile(
      credFile,
      '`gcloud auth application-default login`',
      scopes,
      baseClient,
    );
  }

  return await clientViaMetadataServer(baseClient: baseClient);
}