Skip to content

Instantly share code, notes, and snippets.

@frankie567
Created December 28, 2021 14:50
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie567/c9168544a3d887bcb4f69639bd56234a to your computer and use it in GitHub Desktop.
Save frankie567/c9168544a3d887bcb4f69639bd56234a to your computer and use it in GitHub Desktop.
Generate signed tokens for Cloudflare Stream in Python
import base64
from datetime import datetime
from jwcrypto import jwt, jwk # pip install jwcrypto
b64_jwk = "XXXX" # Base64-encoded JWT you get from Cloudflare Stream API (https://developers.cloudflare.com/stream/viewing-videos/securing-your-stream#step-1-call-the-streamkey-endpoint-once-to-obtain-a-key)
jwk_key = jwk.JWK.from_json(base64.b64decode(b64_jwk))
def get_video_token(video_id: str, lifetime: int = 3600) -> str:
header = {"kid": jwk_key["kid"], "alg": "RS256"}
payload = {
"sub": video_id,
"kid": jwk_key["kid"],
"exp": int(datetime.now().timestamp() + lifetime),
}
token = jwt.JWT(header=header, claims=payload)
token.make_signed_token(jwk_key)
return token.serialize()
@phucth102
Copy link

Thank you! It's helpful for me.

@frankie567
Copy link
Author

Thank you @phucth102 🙏

@kieri097
Copy link

Very helpful, thanks a lot @frankie567!!

@padaliyajay
Copy link

Thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment