oauth2.0 如何从AWS Lambda函数中授权Google Drive API?

8fq7wneg  于 2023-08-02  发布在  Go
关注(0)|答案(1)|浏览(138)

我正在编写一个lambda函数(用于与API网关集成),它需要连接到Google Drive。我使用googleapiclient库在我的计算机上本地运行工作代码。我有一个credentials.json和client_secret.json文件,我正在使用OAuth2连接到Google云端硬盘。然而,当我将这些文件上传到Lambda函数时,我的代码得到一个错误,它是一个只读文件系统,代码试图写入credentials.json。我怎么才能让它工作?是否有一种方法可以远程存储和访问这些文件,例如在S3上?或者有一种方法可以让验证码不需要修改credentials.json?这是我用于Google Drive授权的代码:

from googleapiclient import discovery, errors
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
from httplib2 import Http
from oauth2client import client, file, tools

credentials_file_path = './credentials.json'
clientsecret_file_path = './client_secret.json'

SCOPE = 'https://www.googleapis.com/auth/drive'

store = file.Storage(credentials_file_path)
credentials = store.get()

if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(clientsecret_file_path, SCOPE)
    credentials = tools.run_flow(flow, store)
http = credentials.authorize(Http())
drive = discovery.build('drive', 'v3', http=http)

字符串

vmdwslir

vmdwslir1#

你的要求有两点-
1.读取初始凭据文件和
1.在凭据无效或找不到凭据时将新数据写入文件。
对于第一部分,即阅读文件,您可以将文件保存在与lambda函数python文件相同的根目录中(您已经在这样做了)。
但是对于第二部分,即写入文件,它应该在位于/tmp文件夹中的文件中完成,因为lambda运行时环境不允许您写入根目录。更多详细信息来自AWS文档-https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html
因此,您的代码应该写入类似'/tmp/credentials.json'的文件。
注意:您也可以使用S3存储桶来读写文件。

另一个更好的方法是

与其将凭证存储在lambda运行时环境的文件存储中,不如使用AWS Secrets Manager等服务来存储和检索机密文件。详细信息-https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html
这将更加安全,并被视为最佳实践。

相关问题