首页 > 解决方案 > 在谷歌云函数中生成JWT - python

问题描述

我编写了一个脚本并将其上传到 GCFunctions。现在,我的一个函数是使用PyJWT 库来为 GCP API 调用生成 JWT,问题是我每次运行函数时都会遇到错误。当我将 pyjwt 添加到“requirements.txt”时,出现错误:“找不到算法 RS256”, 然后我尝试添加密码学(pyjwt 使用的加密库),还尝试了 pycrypto(用于 RS256 注册)但仍然没有什么。我会很感激这里的一些帮助!甚至对 GCP API 调用中其他身份验证方法的建议也会很棒! 提前致谢!!

编辑:顺便说一句-该函数在 Python3.7 上运行

这是我的 requirements.txt 文件的内容(依赖项)

# Function dependencies, for example:
# package>=version
requests==2.21.0
pycrypto
pyjwt==1.7.1
pyjwt[crypto]
boto3==1.11.13

这是我在尝试添加pyjwt[crypto]并再次运行脚本时遇到的异常: 在此处输入图像描述

标签: pythonrestgoogle-cloud-platformjwtgoogle-cloud-functions

解决方案


找到了让它工作的方法。在这里发布给那些将来会面对它的人......我最终决定上传一个包含代码文件 + requirements.txt + 服务帐户 JSON Credentials 文件的 zip 文件,并将以下库添加为依赖项(到 requirements.txt ):oauth2client,google-api-python-client。

我是这样做的:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
import logging

# set the service with the credentials
credentials = GoogleCredentials.from_stream("my_creds.json")
service = discovery.build('compute', 'v1', credentials=credentials)
# block errors printing for 'googleapicliet.discovery'
logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)

def main(event, context):
    # Project ID for this request.
    project = '<project_id>'  

    # The name of the zone for this request.
    zone = '<zone>'

    # Name of the instance resource to return.
    instance = '<instance-id>'

    request = service.instances().get(project=project, zone=zone, instance=instance)
    response = request.execute()

    # print only network details of the instance
    print("'{}' Network Details: {}".format(response['name'], response['networkInterfaces'][0]['accessConfigs'][0]))

推荐阅读