Skip to content

JWT — alert when access token is about to expire

A service talks to a third-party API via JWT, token lives 24h and someone occasionally renews it manually. If they forget — the pipeline breaks at 3am.

Recipe

python
#!/usr/bin/env python3
# /opt/jwt-expiry-check.py — runs from cron every 30 min
import base64, json, os, sys, time, urllib.request

TOKEN = os.environ['SVC_JWT']                # secret in env, not source
WARN_HOURS = 6                                # alert when < N hours left
WEBHOOK = os.environ.get('HEARTBEAT_URL', '')

def decode_exp(token: str) -> int:
    payload = token.split('.')[1]
    payload += '=' * (-len(payload) % 4)      # base64url padding
    data = json.loads(base64.urlsafe_b64decode(payload))
    return int(data.get('exp', 0))

exp = decode_exp(TOKEN)
left_hours = (exp - int(time.time())) / 3600

if left_hours < WARN_HOURS:
    msg = f'JWT истекает через {left_hours:.1f} ч (exp={exp})'
    if WEBHOOK:
        urllib.request.urlopen(
            urllib.request.Request(WEBHOOK,
                data=json.dumps({'text': msg}).encode(),
                headers={'Content-Type': 'application/json'}),
            timeout=5)
    sys.exit(2)
print(f'OK ({left_hours:.1f}h left)')

Same thing in Enterno.io

Replace the cron+Slack pair with an Enterno heartbeat on a 30-minute schedule and a threshold alert. You see the "forgot-to-renew" history alongside the rest of your monitors instead of buried in Slack.

Set up HTTP monitor → ← All recipes

Related recipes