How to oAuth Google API from Lambda AWS?

若如初见. 提交于 2019-11-30 15:19:35

You should create a service account. Those are designed especially for server-to-server communication. Documentation can be found here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

The problems with the solutions from other answers are:

  • API keys are insecure
  • Access tokens (e.g. obtained by the CLI command gcloud auth print-access-token) expire. Since Lambdas are stateless, there's no way to store a token temporarily and refresh it when it's expired.

You have to do 2 steps specified in here, if you follow correctly you will get this done.

First, (only the first time) you need to set up your project and download the GOOGLE APPLICATION CREDENTIALS you will result with one json file with auth information inside, lets suppose you call it project.json

Now you will need to execute some commands to get access tokens, download and install Cloud SDK to have access to those commands.

 gcloud auth activate-service-account --key-file=/home/panchicore/project.json

then

gcloud auth print-access-token

you will get your key at this point, now we can use it in the next step:

Second, Make a Translation API request: (how I did it and tested with python requests)

import requests

key = "KEY GOT WITH gcloud auth print-access-token"

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {}'.format(key)
}

url = 'https://translation.googleapis.com/language/translate/v2'

data = {
  'q': 'The quick brown fox jumped over the lazy dog.',
  'source': 'en',
  'target': 'es',
  'format': 'text'
}

res = requests.post(url, json=data, headers=headers)

print res.content
>>> El rápido zorro marrón saltó sobre el perro perezoso.

Hope it helps.

The easier way is using api keys to authenticate. https://cloud.google.com/docs/authentication/api-keys

You can make requests to some google apis like this (javascript)

const request = require('request')
request.post(`https://language.googleapis.com/v1beta2/documents:analyzeSentiment?key=${process.env.GOOGLE_API_KEY || ''}`, 
{
    json : true,
    body : {
        document : document
    }
},
(error, response, body) => {
    console.log(body)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!