Call Google Cloud Functions with C#

When using C# and .NET to consume IAM protected cloud functions in Google Cloud Platform (GCP), a lot of information unpacking is needed. In particular, when calls are made from outside of GCP. I hope I can provide a little guidance.

Authentication

Cloud function invocation is secured by IAM (acronym of Cloud Identity and Access Management). Callers of HTTP Functions need the IAM role roles/cloudfunctions.invoker.

Function requests should carry a resource specific access token, a bearer token. The resource's identifier is called audience. For HTTP functions the resource identifier/audience is the endpoint's URL. In C#, authentication is provided by the Google.Apis.Auth NuGet package(opens in a new window).

Once the bearer token is acquired, the cloud function request can be sent, with the token included in the Authorization HTTP header. AuthenticationHeaderValue in namespace System.Net.Http.Headers, provide functionality for formatting the HTTP request header.

Cloud function request

The below example fetches an access token and then invokes a HTTP Function. Authentication credentials are catered by a service account key(opens in a new window).

Post file to cloud function #

C#
using Google.Apis.Auth.OAuth2;

async Task PostFile(FileInfo file)
{
  var functionUrl = "https://[REGION].cloudfunctions.net/my-function";
  var credentialsPath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");

  var oidcToken = await GoogleCredential
    .FromFile(credentialsPath)
    .GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(functionUrl));

  var token = await oidcToken.GetAccessTokenAsync();

  using var stream = File.OpenRead(file.FullName);
  var formData = new MultipartFormDataContent(Guid.NewGuid().ToString("N"));
  formData.Add(new StreamContent(stream), "file", file.Name);

  using var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
  await client.PostAsync(functionUrl, formData);
}

Subpar docs

Put politely, the .NET API docs for Google Cloud Platform has improvement potential. Often, to understand what APIs and NuGet packages to use and how, involves tying together code samples from other programming languages and documentation from multiple sources. Exploration can be confusing, but the docs site for Google Cloud Libraries for .NET(opens in a new window)seems to be a decent starting point.

I hope I've now assisted somewhat, if nothing else than by showing how to call secured cloud functions.