Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting GOOGLE_APPLICATION_CREDENTIALS for an MVC site hosted on azure

Title says it all pretty much.

I tried uploading the json file to azure storage and referenced it's url when setting the GOOGLE_APPLICATION_CREDENTIALS environment variable under app settings, but when remotely debugging the site, apparently the url/directory was not in an acceptable format. I can’t store the json file locally either because the website doesn’t have any idea about my C drive directories.

Where should I store this file so that I can set the GOOGLE_APPLICATION_CREDENTIALS environment variable for my azure site to the directory of the json file?

like image 536
Harry Stuart Avatar asked Nov 18 '22 07:11

Harry Stuart


2 Answers

The ToChannelCredentials() approach does not seem to work anymore, so I come up with an other solution that works on Azure. I create a text file in the /bin folder of my Azure server with the credentials and then I point the environment variable to this file. Google Cloud API will use this for the default credentials.

string json = @"{
    'type': 'service_account',
    'project_id': 'xxx',
    'private_key_id': 'xx',
    'private_key': 'xxx',
     ...
}";  // this is the content of the json-credentials file from Google

// Create text file in projects bin-folder 
var binDirectory = Path.GetDirectoryName(Assembly.GetCallingAssembly().CodeBase);
string fullPath = Path.Combine(binDirectory, "credentials.json").Replace("file:\\","");

using (StreamWriter outputFile = new StreamWriter(fullPath, false)) {
    outputFile.WriteLine(json);
}

// Set environment variabel to the full file path
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", fullPath);

// Now you can call the service and it will pick up your credentials
TranslationServiceClient client = TranslationServiceClient.Create(); 
like image 106
FFischer Avatar answered Dec 20 '22 16:12

FFischer


If anyone is wondering how to handle the Google's credentials smoothly in .Net applications instead of strange way of using the file on server, this is how I solved it for Translation Service. Other services must follow same principle:

  • store the content of the Google credentials json file as an environment variable in settings.json/azure configuration for your app (using ' ' instead of " " for inner text):

    "GOOGLE_APPLICATION_CREDENTIALS": "{'type': 'service_account','project_id': ...}"
    
  • create and return the client:

      var credential = GoogleCredential.FromJson(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"));
      var channelCredentials = credential.ToChannelCredentials();
      var channel = new Channel(TranslationServiceClient.DefaultEndpoint.ToString(), channelCredentials);
      return TranslationServiceClient.Create(channel);
    

Took a while for me to figure it our. Hope it helps.

like image 37
CageE Avatar answered Dec 20 '22 18:12

CageE