Search code examples
c#.netgoogle-cloud-platformgoogle-speech-api

Is It Possible To Manually Supply a GoogleCredential To SpeechClient (In .NET API)?


All of the documentation for SpeechClient that I've found involves either running a command line after downloading the SDK, or awkwardly setting up a "GOOGLE_APPLICATION_CREDENTIALS" environment variable to point to a local credential file.

I hate the environment variable approach, and instead want a solution that loads a shared, source-controlled dev account file from the application root. Something like this:

var credential = GoogleCredential.FromStream(/*load shared file from app root*/);
var client = SpeechClient.Create(/*I wish I could pass credential in here*/);

Is there a way to do this so that I don't have to rely on the environment variable?


Solution

  • Yes, by converting the GoogleCredential into a ChannelCredentials, and using that to initialize a Channel, which you then wrap in a SpeechClient:

    using Grpc.Auth;
    
    //...
    
    GoogleCredential googleCredential;
    using (Stream m = new FileStream(credentialsFilePath, FileMode.Open))
        googleCredential = GoogleCredential.FromStream(m);
    var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.Host,
        googleCredential.ToChannelCredentials());
    var speech = SpeechClient.Create(channel);
    

    Update 2018-02-02 https://cloud.google.com/docs/authentication/production now shows all they possible ways to authenticate to a Google Cloud Service, including a sample like this one.