Created
April 22, 2022 16:02
-
-
Save g-a-d/602b11005b1456c3183caecd4ecf236a to your computer and use it in GitHub Desktop.
Get Github API token for a Github app (python)
This file contains 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
def get_github_token(app_id, pem_file, organization_slug, repository, private_key_file): | |
jwt = get_jwt_token(app_id, private_key_file) | |
installation = requests.get(f'https://api.github.com/orgs/{organization_slug}/installation', headers={'Authorization': f'Bearer {jwt}'}) | |
access_tokens_url = installation.json()['access_tokens_url'] | |
# values for the permissions are documented here: https://docs.github.com/en/rest/overview/permissions-required-for-github-apps | |
data = {'repository': repository, 'permission': {'contents': 'write'}} | |
token_request = requests.post(access_tokens_url, headers={'Authorization': f'Bearer {jwt}'}, json=data) | |
token = token_request.json()['token'] | |
return token | |
def get_jwt_token(app_id, private_key_file): | |
import sys | |
import jwt | |
import time | |
from cryptography.hazmat.primitives.serialization import load_pem_private_key | |
from cryptography.hazmat.backends import default_backend | |
current_time = int(time.time()) | |
payload = { | |
'iat': current_time, | |
'exp': current_time + (10 * 60), | |
# GitHub App's identifier – you can get it from the github application dashboard | |
'iss': app_id, | |
} | |
with open(private_key_file) as fd: | |
private_key_contents = fd.read().encode() | |
cert_obj = load_pem_private_key(private_key_contents, password=None, backend=default_backend()) | |
encoded = jwt.encode(payload, private_key_contents, algorithm='RS256') | |
return(encoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note there's no error checking on this; add some before running in production.