Search code examples
c#.net-coregoogle-cloud-pubsub

Specifying Google Credentials When Creating a SubscriberClient using C# Client Library


I've setup a GCP PubSub processor for our service and it creates a SubscriberClient like so

var subscriptionClient = await SubscriberClient.CreateAsync(subscriptionName);.

And I have the GOOGLE_APPLICATION_CREDENTIALS environment variable set and pointing at a valid SA key. Everything works as expected.

However, how can I go about not using/relying on the GOOGLE_APPLICATION_CREDENTIALS environment variable on my local machine?

The Cloud Storage Client libraries allow you to create a storage client like so StorageClient.Create(GoogleCredentials gcpCredentials); and I was looking for something like this with the PubSub client libraries but did not find anything. There is ChannelCredentials but that does not appear to be for this purpose.

I do see that SubscriberServiceApiClientBuilder allows you to specify JsonCredentials but I'm not using that client for my use case. As the SubscriberClient and PublisherClient are more suitable for my purpose given the following from the documentation:

PublisherClient and SubscriberClient provide simpler APIs for message publishing and subscribing. These classes offer considerably higher performance and simplicity, especially when working with higher message throughput.

Thanks


Solution

  • Creating the ChannelCredentials manually, in a similar fashion as done in the PublisherClient and passing in ClientCreationSettings initialized with credentials set using GoogleCredentials.ToChannelCredentials() does the job.

    var subscriptionName = SubscriptionName.FromProjectSubscription("projectId", "subscriptionId");
    
    // create GoogleCredentials
    var gcpCredentials = <code that creates valid GoogleCredentials>;
    
    // create ClientCreationSettings with credentials based on the GoogleCredentials created above
    var settings = new SubscriberClient.ClientCreationSettings(credentials: gcpCredentials.ToChannelCredentials());
    
    var client = await SubscriberClient.CreateAsync(<SubscriptionName>, settings);
    

    I asked this question in the GitHub googleapis/google-api-dotnet-client repo as well. if you want a bit more information about it: GitHub Issue 1764 Link