JWT Utitilies
Missil uses the excellent Python-jose as backend to offer some JWT conveniences.
Encode JWT Token
Usage Example
from datetime import datetime
from missil import encode_jwt_token
SECRET_KEY = "averysecretkey"
base_date = datetime(2094, 2, 26)
claims = {"name": "John Doe", "userPrivileges": {"finances": 1}}
token = encode_jwt_token(claims, SECRET_KEY, 8, base=base_date)
print(token)
API Reference
missil.encode_jwt_token
Create a JWT token.
PARAMETER | DESCRIPTION |
---|---|
claims |
Token user data.
TYPE:
|
secret |
Secret key to sign the token.
TYPE:
|
exp |
Token expiration in hours.
TYPE:
|
base |
Token expiration base datetime, where the final datetime is given by base + exp, by default datetime.now(timezone.utc)
TYPE:
|
algorithm |
Encode algorithm, by default "HS256"
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
description |
Source code in missil/jwt_utilities.py
Decode JWT Token
Usage Example
from missil import decode_jwt_token
TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJ1c2VyUHJpdmlsZWdlcyI6eyJmaW5hbmNlcyI6MX0sImV4cCI6MzkxODY3MjAwMH0.BWkskBJZj68mLaxqgdO0occL_FY8RSdEnqNSC6Swxh0"
SECRET_KEY = "averysecretkey"
decoded_token = decode_jwt_token(TOKEN, SECRET_KEY)
print(decoded_token) # {'name': 'John Doe', 'userPrivileges': {'finances': 1}, 'exp': 3918672000}
API Reference
missil.decode_jwt_token
Decode a JWT Token using Python-jose.
PARAMETER | DESCRIPTION |
---|---|
token |
Token to be decoded.
TYPE:
|
secret_key |
Secret key to decode the signed token.
TYPE:
|
algorithm |
Decoding algoritgm. See Python-jose docs for more details.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict[str, Any]
|
Decoded claims. |
RAISES | DESCRIPTION |
---|---|
TokenErrorException
|
The token signature has expired. |
TokenErrorException
|
The token claim is invalid. |
TokenErrorException
|
Generalist exception. The token signature is invalid. |
TokenErrorException
|
Most generalist exception. The token is invalid. |