authenticationgoogle-cloud-platformgoogle-translation-api

Google translate API V3: How to authenticate service account from file stream


The default way for authenticating a service account for using the Google Translate V3 API is by means of an environment variable. This env var, called GOOGLE_APPLICATION_CREDENTIALS, points to a json file with the credentials, as described here: https://cloud.google.com/docs/authentication/production

However, how can I use the required credentials when using a file in a different location? I am able to create the credentials object from a FileStream alright, as described in the google documentation. However, using this credentials object is only docmented for google cloud storage. The Builder for the TranslateTextRequest does not accept such a credentials object. https://googleapis.dev/dotnet/Google.Cloud.Translate.V3/2.0.0/api/Google.Cloud.Translate.V3.TranslateTextRequest.html

The only workaround would be to copy the file to the location specified in the env var, but this seems odd and would fail when that variable isn't set.


Solution

  • So, at last, I have been able to figure this problem out.

    @JohnHanley Unfortunately, the class TranslationServiceClientBuilder was not available in my environment. Maybe it is DotNet specific. However, the hint was still very helpful, because I found another Builder which creates an instance of TranslationServiceSettings, which in turn has a static factory method, which in turn can be used to instantiate a TranslationServiceClient.

    The following is the full solution for how to create a TranslationServiceClient from the file path to the Google JSON credentials file.

    TranslationServiceSettings settings = TranslationServiceSettings.newBuilder().setCredentialsProvider(new CredentialsProvider() {
        @Override
        public Credentials getCredentials() throws IOException {
            GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsFileAbsPath))
                    .createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
    
            return credentials;
        }
    }).build();
    
    TranslationServiceClient translationServiceClient = TranslationServiceClient.create(settings);
    

    The anonymous class could also be replaced with a Lambda expression, of course.

    @PjotrS Sorry about the confusion. The file I was referring to was the JSON credentials file, not the file to be translated.