Use JSON Web Tokens

Use JSON web tokens.

In [1]:
import jwt

jwt.encode?

Signature:
jwt.encode(
    payload,
    key,
    algorithm='HS256',
    headers=None,
    json_encoder=None,
)
Type:      method
In [2]:
(encoded := jwt.encode({"some": "payload"}, "secret"))
Out[2]:
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U'
In [3]:
jwt.decode(encoded, "secret", algorithms=["HS256"])
Out[3]:
{'some': 'payload'}

Set an expiration date.

In [4]:
from datetime import datetime, timedelta
import time
import arrow
In [5]:
(
    encoded := jwt.encode(
        {"exp": (exp := datetime.utcnow() + timedelta(seconds=3))}, "secret"
    )
)
Out[5]:
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1Nzc3MDg2ODV9.3sInaD8S16T9Iva3I-OI0-4BtXbxh7PGIkHfepXNGGQ'
In [6]:
print(len(encoded))
105
In [7]:
time.sleep(4)  # Allow time to expire.
In [8]:
try:
    jwt.decode(encoded, "secret")
except jwt.ExpiredSignatureError:
    print(f"Signature expired {arrow.get(exp).humanize()}.")
Signature expired just now.