ruby 在python中从pem文件生成JWT

o3imoua4  于 2023-06-05  发布在  Ruby
关注(0)|答案(1)|浏览(393)

我正在尝试将一些代码从Ruby转换为Python。代码用于从pem文件生成JWT令牌。

require 'openssl'
require 'jwt'  # https://rubygems.org/gems/jwt

# Private key contents
private_pem = File.read("YOUR_PATH_TO_PEM")
private_key = OpenSSL::PKey::RSA.new(private_pem)

# Generate the JWT
payload = {
  # issued at time, 60 seconds in the past to allow for clock drift
  iat: Time.now.to_i - 60,
  # JWT expiration time (10 minute maximum)
  exp: Time.now.to_i + (10 * 60),
  # GitHub App's identifier
  iss: "YOUR_APP_ID"
}

jwt = JWT.encode(payload, private_key, "RS256")
puts jwt

我想到了这个

import jwt
import time
import datetime
import OpenSSL

pemfile = open("./utils/private-key.pem", 'r')
keystring = pemfile.read()
pemfile.close()
# print(keystring)
payload = {
    # issued at time, 60 seconds in the past to allow for clock drift
    "iat": time.time() - 60,
    # JWT expiration time (10 minute maximum)
    "exp": time.time() + (10 * 60),
    # GitHub App's identifier
    "iss": "APP_IDENTIFIED"
}

key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, keystring)

token = jwt.encode(payload, key, algorithm='RS256')

print("=============================")
print(token)
print("=============================")

我不断地遇到这个错误

Traceback (most recent call last):
  File "/home/junior/dev/cranom/backend/intergrations/github/gh-token.py", line 21, in <module>
    token = jwt.encode(payload, key, algorithm='RS256')
  File "/home/junior/dev/cranom/backend/.venv/lib/python3.10/site-packages/jwt/api_jwt.py", line 64, in encode
    return api_jws.encode(json_payload, key, algorithm, headers, json_encoder)
  File "/home/junior/dev/cranom/backend/.venv/lib/python3.10/site-packages/jwt/api_jws.py", line 133, in encode
    key = alg_obj.prepare_key(key)
  File "/home/junior/dev/cranom/backend/.venv/lib/python3.10/site-packages/jwt/algorithms.py", line 249, in prepare_key
    raise TypeError("Expecting a PEM-formatted key.")
TypeError: Expecting a PEM-formatted key.

我基本上是按照Github文档中关于如何认证Github应用程序的教程来做的
https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps

4ktjp1zp

4ktjp1zp1#

在我的例子中,我使用了

keystring = jwt.jwk_from_pem(pemfile.read())

然后令牌变成

jwt_instance = jwt.JWT()
token = jwt_instance.encode(payload, keystring , algorithm='RS256')

这不需要OpenSSL导入。然后可以在GitHub授权令牌请求的头部中使用该令牌,例如:

import requests
url="https://api.github.com/app/installations/APP_IDENTIFIED/access_tokens"
headers = {
    "Authorization": "Bearer %s" % token
}
response = requests.post(url, headers=headers)
auth_token = response.json()["token"]

相关问题