How to sign an API Token with a new expiry header
The following Python code can be used to decode an existing JWT, reset the exp claim (expiry date) and re-sign the token with the same header information (incl. kid and alg). The aim is a new, valid token with an updated expiry date:
from base64 import urlsafe_b64decode, b64encode from json import loads import datetime from jwt import encode, decode from typing import Dict, Any def pad_base64url(b64string: str) -> str: return b64string + '=' * (-len(b64string) % 4) def extract_header(jwt_token: str) -> Dict[str, Any]: header_b64 = jwt_token.split('.')[0] padded_header = pad_base64url(header_b64) header_json = urlsafe_b64decode(padded_header) return loads(header_json) def encode_secret(secret: str) -> bytes: return b64encode(secret.encode()) token: str = "eyJraWQiOiI1Zjc.…" secret: bytes = encode_secret("d4cHsO5QTCt5eZg1…") payload: Dict[str, Any] = decode(token, secret, algorithms=["HS512"], options={"verify_exp": False}) payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(hours=1) new_token: str = encode(payload, secret, headers=extract_header(token), algorithm="HS512") print(new_token)
This is particularly useful if you want to use short-lived tokens - for security reasons, for example, to deliberately limit the validity period of tokens and thus minimise the risk of theft or misuse.
API
JWT
Security
eSagu API