How to oAuth Google API from Lambda AWS?

此生再无相见时 提交于 2019-11-29 14:46:20

问题


I am building Alexa Skill for Google calendar. The client side code works as expected on local machine because I can authenticate the local machine using the link. But, when I deploy the code on AWS Lambda there is no way that I can authenticate as I cannot input code via AWS console.

I am getting trouble in setting up authentication of Google Calendar API when deployed on AWS lambda.

This documentation doesn't help much to me Google Implementing Server Side Authentication


回答1:


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.



回答2:


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.




回答3:


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)
})


来源:https://stackoverflow.com/questions/42170504/how-to-oauth-google-api-from-lambda-aws

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!