Skip to content

Instantly share code, notes, and snippets.

@tcarreira
Created December 4, 2020 14:22
Show Gist options
  • Save tcarreira/0eaec2b7631f388810b18ba1a096d980 to your computer and use it in GitHub Desktop.
Save tcarreira/0eaec2b7631f388810b18ba1a096d980 to your computer and use it in GitHub Desktop.
Generate a JWT token signed by a random self-signed key (RS256)
#!/usr/bin/env python3
import subprocess
from datetime import datetime, timedelta
import jwt
subprocess.call(
"openssl genrsa -out private.pem 1024".split(" "), stderr=subprocess.DEVNULL
)
subprocess.call(
"openssl rsa -in private.pem -outform PEM -pubout -out public.pem".split(" "),
stderr=subprocess.DEVNULL,
)
privkey = ""
with open("private.pem", "r") as f:
privkey = f.read()
pubkey = ""
with open("public.pem", "r") as f:
pubkey = f.read()
privkey = "\n".join([l.lstrip() for l in privkey.split("\n")])
pubkey = "\n".join([l.lstrip() for l in pubkey.split("\n")])
print("")
print("=== Public Key: ===")
print(pubkey)
iss="local"
aud = "[email protected]"
payload = {
"iss": iss,
"iat": 1577836800,
"exp": 3155760000,
"aud": aud,
"cid": "abc123def456==",
"sub": "local@local",
}
token = jwt.encode(payload, privkey, algorithm="RS256")
print("")
print("=== JWT Token: ===")
print(token)
print("")
print("=== JWT token successfully decoded and verified with public key: ===")
print(
jwt.decode(
token,
key=pubkey,
algorithms="RS256",
issuer=iss,
audience=aud,
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment