Last active
October 8, 2024 17:54
-
-
Save ProfAvery/15992d20962b52e04523419df4939ea6 to your computer and use it in GitHub Desktop.
California State University, Fullerton - CPSC 449 - JWK and JWT generation
This file contains hidden or 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 python | |
import os | |
import sys | |
import json | |
import datetime | |
def usage(): | |
program = os.path.basename(sys.argv[0]) | |
print(f"Usage: {program} USERNAME USER_ID ROLE...", file=sys.stderr) | |
def expiration_in(minutes): | |
creation = datetime.datetime.now(tz=datetime.timezone.utc) | |
expiration = creation + datetime.timedelta(minutes=minutes) | |
return creation, expiration | |
def generate_claims(username, user_id, roles): | |
_, exp = expiration_in(20) | |
claims = { | |
"aud": "krakend.local.gd", | |
"iss": "auth.local.gd", | |
"sub": username, | |
"jti": str(user_id), | |
"roles": roles, | |
"exp": int(exp.timestamp()), | |
} | |
token = { | |
"access_token": claims, | |
"refresh_token": claims, | |
"exp": int(exp.timestamp()), | |
} | |
output = json.dumps(token, indent=4) | |
print(output) | |
if __name__ == "__main__": | |
if len(sys.argv) < 4: | |
usage() | |
sys.exit(1) | |
generate_claims(sys.argv[1], sys.argv[2], sys.argv[3:]) |
This file contains hidden or 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 python | |
import os | |
import sys | |
import json | |
from jwcrypto import jwk | |
def usage(): | |
program = os.path.basename(sys.argv[0]) | |
print(f"Usage: {program} KEY_ID...", file=sys.stderr) | |
def generate_keys(key_ids): | |
keys = [jwk.JWK.generate(kid=key_id, kty="RSA", alg="RS256") for key_id in key_ids] | |
private_keys = [json.loads(exported) for exported in [key.export() for key in keys]] | |
public_keys = [ | |
json.loads(exported) | |
for exported in [key.export(private_key=False) for key in keys] | |
] | |
print("private.json:\n") | |
json.dump({"keys": private_keys}, sys.stdout, indent=4) | |
print("\n" * 2) | |
print("public.json:\n") | |
json.dump({"keys": public_keys}, sys.stdout, indent=4) | |
if __name__ == "__main__": | |
if len(sys.argv) == 1: | |
usage() | |
sys.exit(1) | |
generate_keys(sys.argv[1:]) |
This file contains hidden or 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
jwcrypto==1.5.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment