Last active
January 27, 2022 23:54
-
-
Save jay0lee/1587db4e5b48918e62b5cb144726e982 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
### This script requires PyJWT. Install it by running: | |
### | |
### pip3 install PyJWT | |
### | |
### Example usage on Linux with curl to call Admin SDK Directory API users.get() | |
### | |
### curl -vvvv \ | |
### -H "accept: application/json" \ | |
### -H "Authorization: Bearer $(python3 ~/test-jwt.py \ | |
### --file ./oauth2service.json \ | |
### --audience https://admin.googleapis.com/)" \ | |
### https://www.googleapis.com/admin/directory/v1/users?domain=YOURDOMAIN.COM | |
### | |
import argparse | |
import json | |
import os | |
import time | |
import jwt | |
parser = argparse.ArgumentParser(description='Generate a JWT Header for Google APIs') | |
parser.add_argument('--file', | |
help='Service account credential file.', | |
required=True, | |
dest='cred_file') | |
parser.add_argument('--audience', | |
help='Audience of the JWT assertion.', | |
default='https://admin.googleapis.com/', | |
dest='audience') | |
args = parser.parse_args() | |
if not os.path.isfile(args.cred_file): | |
print(f'ERROR: {args.cred_file} does not exist') | |
with open(args.cred_file, 'r') as f: | |
sa_info = json.load(f) | |
iat = time.time() | |
exp = iat + 3600 | |
payload = {'iss': sa_info['client_email'], | |
'aud': args.audience, | |
'iat': iat, | |
'exp': exp, | |
'sub': sa_info['client_email']} | |
headers = {'kid': sa_info['private_key_id']} | |
signed_jwt = jwt.encode(payload, | |
sa_info['private_key'], | |
headers=headers, | |
algorithm='RS256') | |
print(signed_jwt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment