Created
October 16, 2023 11:39
-
-
Save edubxb/8e287980768851fc3312c20e375f48b9 to your computer and use it in GitHub Desktop.
Python script for getting a GitHub API token for an GitHub application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
## related docs: ## | |
## https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app | |
## https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation | |
################### | |
import sys | |
import time | |
import jwt | |
import requests | |
# Get PEM file path | |
if len(sys.argv) > 1: | |
pem = sys.argv[1] | |
else: | |
pem = input("Enter path of private PEM file: ") | |
# Get the App ID | |
if len(sys.argv) > 2: | |
app_id = sys.argv[2] | |
else: | |
app_id = input("Enter your APP ID: ") | |
# Get the App Installation ID | |
if len(sys.argv) > 3: | |
installation_id = sys.argv[3] | |
else: | |
installation_id = input("Enter your APP Installation ID: ") | |
# Open PEM | |
with open(pem, "rb") as pem_file: | |
signing_key = jwt.jwk_from_pem(pem_file.read()) | |
payload = { | |
# Issued at time | |
"iat": int(time.time()), | |
# JWT expiration time (10 minutes maximum) | |
"exp": int(time.time()) + 600, | |
# GitHub App's identifier | |
"iss": app_id, | |
} | |
# Create JWT | |
jwt_instance = jwt.JWT() | |
encoded_jwt = jwt_instance.encode(payload, signing_key, alg="RS256") | |
# Get an API Token | |
token = requests.post( | |
f"https://api.github.com/app/installations/{installation_id}/access_tokens", | |
headers={ | |
"Accept": "application/vnd.github+json", | |
"X-GitHub-Api-Version": "2022-11-28", | |
"Authorization": f"Bearer {encoded_jwt}", | |
}, | |
).json() | |
print(token["token"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment