Skip to content
This repository was archived by the owner on Jan 4, 2019. It is now read-only.

Commit f19e2bd

Browse files
committed
Encapsulate JWT generation within JWTAuth class
1 parent 5d67162 commit f19e2bd

File tree

2 files changed

+42
-35
lines changed

2 files changed

+42
-35
lines changed

auth.py

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,54 @@
11
#!/usr/bin/env python
22
# -*- coding: utf8 -*-
33

4-
import requests
4+
"""
5+
Authenticate as a GitHub App:
6+
https://developer.github.com/apps/building-github-apps/authentication-options-for-github-apps/#authenticating-as-a-github-app
7+
"""
8+
9+
import os
10+
import time
11+
12+
import jwt
513

6-
import jsonwebtoken
14+
import requests
715

816

917
class JWTAuth(requests.auth.AuthBase):
10-
def __call__(self, r):
11-
r.headers['Authorization'] = 'bearer {}'.format(jsonwebtoken.generate())
18+
def __init__(self, iss, key, expiration=10 * 60):
19+
self.iss = iss
20+
self.key = key
21+
self.expiration = expiration
22+
23+
def generate_token(self):
24+
# Generate the JWT
25+
payload = {
26+
# issued at time
27+
'iat': int(time.time()),
28+
# JWT expiration time (10 minute maximum)
29+
'exp': int(time.time()) + self.expiration,
30+
# GitHub App's identifier
31+
'iss': self.iss
32+
}
33+
34+
tok = jwt.encode(payload, self.key, algorithm='RS256')
35+
36+
return tok.decode('utf-8')
37+
38+
def __call__(self, r):
39+
r.headers['Authorization'] = 'bearer {}'.format(self.generate_token())
1240
return r
1341

42+
with open(os.environ['PRIVATE_KEY_FILE']) as fp:
43+
private_pem = fp.read()
44+
45+
authorization = JWTAuth(
46+
iss=os.environ['APP_ID'],
47+
key=private_pem)
48+
1449
response = requests.get('https://api.github.com/app',
15-
auth=JWTAuth(),
50+
auth=authorization,
1651
headers=dict(accept='application/vnd.github.machine-man-preview+json'))
52+
53+
# Print the response
1754
print(response.json())

jsonwebtoken.py

Lines changed: 0 additions & 30 deletions
This file was deleted.

0 commit comments

Comments
 (0)