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

2

6

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.

Luttrell answered 18/8, 2018 at 3:30 Comment(0)
S
5

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/*"],
Stowe answered 24/1, 2020 at 0:46 Comment(1)
Your solution does not work for me with my API key which I created in Cloud Console for the newly created project. I enabled a payed account with a trial period, but it still refuses to work. Where is my mistake?Heckman
I
2

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"
Inserted answered 18/10, 2018 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.