DevToolsForYou

JWT Encoder and Decoder in Python — Code Examples

JWT Encoder and Decoder in PythonUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

PyJWT is the standard Python JWT library. Pass the algorithm explicitly to jwt.decode to prevent algorithm confusion attacks.

Python
# pip install PyJWT
import jwt
from datetime import datetime, timedelta, timezone

secret = "my-secret-key"
payload = {
    "user_id": 42,
    "name": "Alice",
    "role": "admin",
    "exp": datetime.now(tz=timezone.utc) + timedelta(hours=1),
}

# Sign (encode)
token = jwt.encode(payload, secret, algorithm="HS256")
print(token)  # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# Verify and decode
try:
    decoded = jwt.decode(token, secret, algorithms=["HS256"])
    print(decoded)  # {'user_id': 42, 'name': 'Alice', ...}
except jwt.ExpiredSignatureError:
    print("Token has expired")
except jwt.InvalidTokenError as e:
    print(f"Invalid token: {e}")

# Inspect header without verifying
header = jwt.get_unverified_header(token)
print(header)  # {'alg': 'HS256', 'typ': 'JWT'}
Notes & gotchas
  • Always pass algorithms=[...] to jwt.decode — omitting it was historically exploitable via the 'none' algorithm attack.
  • exp should be a datetime with timezone info (timezone.utc) to avoid deprecation warnings in PyJWT 2+.
  • PyJWT returns str in Python 3 and bytes in Python 2 — use .decode('utf-8') if you see bytes.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages