FAQ - Frequently asked questions

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.

How can I check on the client side if my Token is expired?

In this short example in PHP the exp header of the token would be read and checked if its expiration date has passed.

$token = 'PLACE_YOUR_JWT_HERE';

$tokenPayload = json_decode(base64_decode(explode('.', $token)[1]), true);
if ($tokenPayload['exp'] < time()) {
 throw new RuntimeException("Token \"{$tokenPayload['sub']}\" is expired!");
}