Oauth2在aws lambda上谷歌人api

问题描述 投票:1回答:2

我正在尝试在aws lambda上使用google's people api。由于api需要oauth2,我尝试在本地获取oauth2令牌,然后将其传输到aws lambda:

我用这个函数存储秘密:

from oauth2client.file import Storage
from oauth2client import client, tools

def get_credentials():
    credential_path = os.path.join(SCRIPT_DIR, 'people-api-secret.json')
    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

然后我使用无服务器框架将people-api-secret.json转移到aws lambda。但是当我尝试在lambda上加载秘密时,store.get()返回None。该文件确实存在于AWS上(os.path.isfile(credential_path)返回True)。

是否无法将这些秘密复制到另一台计算机/ IP地址上?如果不是:如果没有采用例如所描述的“完全成熟的方式”,那么使其工作的“最小方式”是什么? here

更新发现这是一个简单的“权限被拒绝”错误lambda:print(open(credential_path).read())产生[Errno 13] Permission denied: '/var/task/people-api-secret.json'。我想这些变量应该放入环境而不是从文件中读取?

python python-3.x oauth-2.0 aws-lambda serverless-framework
2个回答
3
投票

用你正在做的秘密密钥上传你的json,然后执行以下操作:

#import GoogleCredentials
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()
service = discovery.build('people', 'v1', credentials=credentials,cache_discovery=False)

在lambda配置中,将GOOGLE_APPLICATION_CREDENTIALS设置为环境变量键,将凭据json文件名设置为值。

它适用于我使用google api的所有lambda。


0
投票

虽然提供正确的权限可能会有效(根据Tom Melos评论和this github issue)我想把秘密放入环境变量中,因为这被描述为最佳实践。

首先我需要一种获取令牌的方法,所以我运行了这个(需要文件client_secret.json,您可以在this guide之后从google api控制台下载):

from oauth2client import client, tools

class MyStorage(client.Storage):
    def locked_put(self, credentials):
    print("="*70)
    print("client_id: {}\nclient_secret: {}\nrefresh_token: {}".format(
        credentials.client_id, credentials.client_secret, credentials.refresh_token))
    print("="*70)

flow = client.flow_from_clientsecrets('client_secret.json', 'https://www.googleapis.com/auth/contacts.readonly')
flow.user_agent = 'my-user-agent'
storage = MyStorage()
tools.run_flow(flow, storage)

由此产生的三个字符串我放入this guide之后的环境中然后能够这样做:

import os
from oauth2client import client
from apiclient import discovery

client_id = os.environ['GOOGLE_PEOPLE_CLIENT_ID']
client_secret = os.environ['GOOGLE_PEOPLE_CLIENT_SECRET']
refresh_token = os.environ['GOOGLE_PEOPLE_REFRESH_TOKEN']
credentials = client.GoogleCredentials(None, 
    client_id, 
    client_secret,
    refresh_token,
    None,
    "https://accounts.google.com/o/oauth2/token",
    'my-user-agent')
http = credentials.authorize(httplib2.Http())
service = discovery.build('people', 'v1', http=http,
    discoveryServiceUrl='https://people.googleapis.com/$discovery/rest',
    cache_discovery=False)

有关更多详细信息(我个人刚刚学习了Oauth2的基础知识)我有documented here这些请求中发生了什么,以及为什么我们需要refresh_token

© www.soinside.com 2019 - 2024. All rights reserved.