【问题标题】:Generate JWT in Google cloud function - python在谷歌云函数中生成JWT - python
【发布时间】:2020-06-17 10:35:54
【问题描述】:

我编写了一个脚本并将其上传到 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] 并再次运行脚本时遇到的异常: enter image description here

【问题讨论】:

  • 如果您的目标是授权 Google API 调用,您将需要使用访问或身份令牌。签名的 JWT 仅被少数服务接受。这意味着取决于服务的用户凭据或服务帐户。一些服务同时支持。

标签: python rest google-cloud-platform jwt google-cloud-functions


【解决方案1】:

找到了让它工作的方法。把它贴在这里给那些将来会面对它的人...... 我最终决定上传一个包含代码文件 + requirements.txt + 服务帐户 JSON 凭据文件的 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]))

【讨论】:

    【解决方案2】:

    PyJWT installation documentation 中所述,如果您打算对 JWT 进行编码或解码,则应使用以下 pip install 命令将其安装为必需的附加组件以及pyjwt

    pip install pyjwt[crypto]
    

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

    【讨论】:

    • 抛出异常 -.- “找不到加密模块”
    • 您能否编辑您的问题以包含which pipwhich pythonpython --version 的输出?
    【解决方案3】:

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

    here Google 建议避免专门进行授权过程。而是使用适当的客户端库。

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 2019-02-15
      • 1970-01-01
      • 2021-05-09
      • 2020-11-21
      • 2021-03-04
      • 2015-10-27
      • 2021-01-12
      相关资源
      最近更新 更多