Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an authentication token for Google Cloud Translation API within browser (chrome extension)

Tags:

I'm trying to make a Chrome extension that uses the Google Cloud Translation API. I followed a bunch of instructions on many different pages in the docs for Google Translate and for developing Chrome extensions but I still can't figure out how to actually use the API from within a Browser.

The farthest I've gotten was from following part of the Quickstart guide where you create a service account, get a service account key file (downloaded as a .json file), install and initialize the Google SDK, set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the service account JSON key file, and then make a curl request using gcloud auth application-default print-access-token to get an access token to be inputted as part of the request header: "Authorization: Bearer (token here)". Successfully retrieved a translation that way.

But within the environment of an extension you can't run commands like gcloud so that doesn't work. I was able to manually retrieve an access token using the gcloud command, and then paste that into my javascript code as part of the request header (e.g. xmlHttpRequest.setRequestHeader('Authorization', 'Bearer ya29.c.Elr6BRuTfOtherRandomLetters');). But that access token expires after 60 minutes so that doesn't sustainably work.

I also tried using the identity.getAuthToken method (after updating things in manifest.json the way the documentation says to), but that didn't work. Using my service account client ID as the client_id under oauth2 in manifest.json resulted in an "Invalid client ID" error from identity.getAuthToken. On the other hand, generating an OAuth2 Client ID from Google Console, and using myoauth2clientid.apps.googleusercontent.com as the client_id under oauth2 and ["https://www.googleapis.com/auth/cloud-translation", "https://www.googleapis.com/auth/cloud-platform"] as the scopes under oauth2 resulted in an "OAuth2 not granted or revoked" error from identity.getAuthToken.

Generating an API key from the Google Console page, and using that directly as the key parameter of my translation query, didn't even work: I received a "The request is missing a valid API key." error.

I am really at a loss here. Any help would be awesome.

like image 624
Aly Avatar asked Aug 18 '18 03:08

Aly


2 Answers

I (first time poster) also went through the same steps as you but with the help of @magicnumber's answer I came up with a solution to translate text (from any language to English) in my Chrome Extension using an APIkey instead of a service account key file.

First create a translate function (I used the Async -> Await pattern here):

 async function translate(strSourceText,strApiKey)
  {
    var url = `https://translation.googleapis.com/language/translate/v2?key=${strApiKey}`
    let response = await fetch(url, {
      method: 'POST',
      headers : { 
        'Content-Type': 'application/json',
       },
       body: JSON.stringify({
         target: "en",
         format: "text",
         q: strSourceText
       }),
    }); 
    let data = await response.json()
    return data;
  }

Then call the async function which will return a promise E.g.:

query="כלב" //Hebrew word for dog 🐶

translate(query,  "YOURVALIDAPIKEYGOESHERE")
  .then(response => console.log(response.data))
  .catch(reason => console.log(reason.message));

The response from the Google Translation API should look like:

{
  "data": {
    "translations": [
      {
        "translatedText": "Dog",
        "detectedSourceLanguage": "iw"
      }
    ]
  }
}

Lastly, to avoid violating the Content Security Policy, in my case, I had to add the translation API domain to my permissions key in my extension's manifest.json file:

"permissions": ["https://translation.googleapis.com/language/translate/v2/*"],
like image 152
L4ivi Avatar answered Oct 27 '22 00:10

L4ivi


I went through the same steps as you and also can't rely on gcloud for authentication.

What took me past the "The request is missing a valid API key"-error was to use the query syntax described here https://codelabs.developers.google.com/codelabs/cloud-translation-intro/index.html#5

In my case I used:

curl -s -X POST -H "Content-Type: application/json" \
    --data "{
  'q': 'The Great Pyramid of Giza (also known as the Pyramid of Khufu or the
        Pyramid of Cheops) is the oldest and largest of the three pyramids in
        the Giza pyramid complex.',
  'source': 'en',
  'target': 'es',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2?key=YOURVALIDAPIKEYHERE"
like image 44
oflisback Avatar answered Oct 27 '22 00:10

oflisback