はじめに
DocsにはRubyスクリプトが掲載されていたのですが、Pythonを利用したかったためそのサンプルです
GitHub App による認証
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
GitHub App として認証するには、
- PEM フォーマットで秘密鍵を生成
- 秘密鍵を使用して JSON Web Token (JWT) に署名
- JWT を RS256 アルゴリズムを使用してエンコード
Pythonで取得するにあたって以下のパッケージを利用します。
- pyjwt
- cryptography
pip install pyjwt cryptography
import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
with open(YOUR_PATH_TO_PEM, 'r') as f:
pem_bin = f.read().encode()
private_key = serialization.load_pem_private_key(pem_bin, None, default_backend())
unix_time_now = int(time.time())
payload = {
# issued at time, 60 seconds in the past to allow for clock drift
iat: unix_time_now - 60,
# JWT expiration time (10 minute maximum)
exp: unix_time_now + (10 * 60),
# GitHub App's identifier
iss: YOUR_APP_ID
}
jwt = jwt.encode(payload, private_key, algorithm='RS256')
掲載されているサンプルコマンドと同様にPythonから認証されたアプリの情報をAPIから取得します
$ curl -i -H "Authorization: Bearer YOUR_JWT" -H "Accept: application/vnd.github.v3+json" https://api.github.com/app
import urllib.request
# jwt生成部分は冒頭スクリプト
headers = {
"Authorization": f"Bearer {jwt}",
"Accept": "application/vnd.github.v3+json"
}
url = 'https://api.github.com/app'
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request) as response:
content = response.read()