serviceAccountProvider function

MetadataProvider serviceAccountProvider(
  1. String audience,
  2. ServiceAccount serviceAccount, [
  3. AuthenticationOptions? options
])

Metadata provider that authenticates the service client calls with a given ServiceAccount.

When no access token is available, the interceptor will fetch a new token from the given audience (sometimes also called issuer) with the - optionally - provided AuthenticationOptions. If the options are omitted, the default options will be used.

When a token was fetched, the interceptor will only fetch a new token when the lifetime of the token has expired (default 60 minutes).

Implementation

MetadataProvider serviceAccountProvider(String audience, ServiceAccount serviceAccount,
    [AuthenticationOptions? options]) {
  String? token;
  var expiryDate = DateTime.fromMillisecondsSinceEpoch(0);

  return (Map<String, String> metadata, String _) async {
    if (metadata.containsKey(_authorizationHeader)) {
      return;
    }

    if (token == null || expiryDate.isBefore(DateTime.now())) {
      token = await serviceAccount.authenticate(audience, options);
      expiryDate = DateTime.now().add(const Duration(minutes: 59));
    }

    metadata.putIfAbsent(_authorizationHeader, () => 'Bearer $token');
  };
}