Skip to content

Instantly share code, notes, and snippets.

@g-a-d
Created April 22, 2022 16:02
Show Gist options
  • Save g-a-d/602b11005b1456c3183caecd4ecf236a to your computer and use it in GitHub Desktop.
Save g-a-d/602b11005b1456c3183caecd4ecf236a to your computer and use it in GitHub Desktop.
Get Github API token for a Github app (python)
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)
@g-a-d
Copy link
Author

g-a-d commented Apr 22, 2022

Note there's no error checking on this; add some before running in production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment