Skip to content

Instantly share code, notes, and snippets.

@jeff-heienickle
Created August 14, 2023 16:17
Show Gist options
  • Save jeff-heienickle/88e81f8356b1376480f32c349a16654b to your computer and use it in GitHub Desktop.
Save jeff-heienickle/88e81f8356b1376480f32c349a16654b to your computer and use it in GitHub Desktop.
create JWT
import base64
import json
import hmac
import hashlib
encoding = "utf-8"
secret = "<API_KEY_SHARED_SECRET>".encode(encoding)
iat = 1600116847
exp = 1600203247
jwt_header = json.dumps(
{ "alg": "HS256", "typ": "JWT" }, separators=(",", ":")
).encode(encoding)
jwt_payload = json.dumps(
{"userId": "<USER_ID>", "iat": iat, "exp": exp}, separators=(",", ":")
).encode(encoding)
encoded_header_bytes = base64.urlsafe_b64encode(jwt_header).replace(b"=", b"")
encoded_payload_bytes = base64.urlsafe_b64encode(jwt_payload).replace(b"=", b"")
jwt_signature = hmac.digest(
key=secret,
msg=b".".join([encoded_header_bytes, encoded_payload_bytes]),
digest=hashlib.sha256
)
encoded_signature_bytes = base64.urlsafe_b64encode(jwt_signature).replace(b"=", b"")
jwt_returned = (
f"{str(encoded_header_bytes, encoding)}" +
f".{str(encoded_payload_bytes, encoding)}" +
f".{str(encoded_signature_bytes, encoding)}"
)
# Verify this token at https://jwt.io/#debugger-io
print(jwt_returned)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment