Skip to content

Instantly share code, notes, and snippets.

@afaqk9394
Created November 3, 2019 06:10
Show Gist options
  • Select an option

  • Save afaqk9394/c0c885fb3f9a6e8e997b4201a760245e to your computer and use it in GitHub Desktop.

Select an option

Save afaqk9394/c0c885fb3f9a6e8e997b4201a760245e to your computer and use it in GitHub Desktop.
common API authentication mechanisms
import requests
from cryptography.hazmat.backends import default_backend
import jwt
import time
fname = 'devnet-app.2019-09-28.private-key.pem'
pem_str = open(fname, 'r').read()
pem_bytes = pem_str.encode()
private_key = default_backend().load_pem_private_key(pem_bytes, None)
# Encode *anything* using the requires RS256 algorithm
def app_headers():
time_since_epoch_in_seconds = int(time.time())
payload = {
# issued at time
'iat': time_since_epoch_in_seconds,
# JWT expiration time (10 minute maximum)
'exp': time_since_epoch_in_seconds + (10 * 60),
# GitHub App's identifier
'iss': '42354'
}
actual_jwt = jwt.encode(payload, private_key, algorithm='RS256')
headers = {"Authorization": "Bearer {}".format(actual_jwt.decode()),
"Accept": "application/vnd.github.machine-man-preview+json"}
return headers
resp = requests.get('https://github.com/apps/devnet-app', headers=app_headers())
installation_id = 2278268
resp = requests.post('https://api.github.com/installations/{}/access_tokens'.format(installation_id),
headers=app_headers())
headers = {"Authorization": "token {}".format("v1.91d1033fc5a6089aea61bb3364231feba0d69012"),
"Accept": "application/vnd.github.machine-man-preview+json"}
print(headers)
resp = requests.get('https://api.github.com/installation/repositories', headers=headers)
resp = requests.post('https://api.github.com/repos/afaqk9394/devnetassoc/issues/2/labels',
json=["bug"], headers=headers)
print('Code: ', resp.status_code)
print('Content: ', resp.content.decode()[:200])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment