在Google云函数python中生成JWT

2024-10-03 19:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个脚本并上传到GCFunctions。 现在,我的一个函数正在使用PyJWT库为GCP API调用生成JWT, 问题是每次运行函数时都会出现错误。 当我将pyjwt添加到'requirements.txt'时,我得到了一个错误:'Algorithm RS256找不到', 然后我尝试添加加密(pyjwt使用的加密库),也尝试了pycrypto(用于RS256注册),但仍然没有。 我会很感激你的帮助!甚至在GCPAPI调用中提供其他身份验证方法的建议也会很好! 提前感谢

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

以下是my 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]并再次运行脚本时遇到的异常: enter image description here


Tags: 函数txt脚本api错误cryptojwtalgorithm
3条回答

PyJWT installation documentation中所述,如果您计划对JWT进行编码或解码,则应使用以下pip install命令将其作为所需的额外命令与pyjwt一起安装:

pip install pyjwt[crypto]

或者在requirements.txt中添加pyjwt[crypto]作为新行

由于您希望使用GCP API,我建议您使用客户端库,因为在使用客户端库时,身份验证由库本身管理,因为不需要自己管理安全性

here谷歌建议避免明确执行授权过程。而是使用propper客户端库

找到了一个让它工作的方法。把它贴在这里是为了那些将来要面对它的人。。。 我最终决定上传一个zip文件,其中包含代码文件+requirements.txt+服务帐户JSON凭据文件,并将以下库作为依赖项添加到requirements.txt中:oauth2client,google api python客户端

我是这样做的:

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

相关问题 更多 >