Base64url Encodes JWT Segments Without Padding
urlsafe_b64encode with the '=' padding stripped produces JWT-style segments, and decode restores the missing padding before decoding.
Code
import base64
import json
def b64url_encode(data: bytes) -> str:
# 换成 URL 安全字母表,再去掉 '=' 填充
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def b64url_decode(segment: str) -> bytes:
# 解码前按 len % 4 把填充补回来
return base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
header = b64url_encode(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
payload = b64url_encode(json.dumps({"sub": "user_42", "exp": 1767225600}, separators=(",", ":")).encode())
signature = b64url_encode(b"demo-signature-bytes")
token = ".".join([header, payload, signature])
print("token:", token)
decoded = json.loads(b64url_decode(payload))
print("decoded payload:", decoded["sub"], decoded["exp"])
print("header roundtrip:", b64url_decode(header) == b'{"alg":"HS256","typ":"JWT"}')Output
Captured from a sandboxed run of this snippet in the build pipeline.
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzQyIiwiZXhwIjoxNzY3MjI1NjAwfQ.ZGVtby1zaWduYXR1cmUtYnl0ZXM
decoded payload: user_42 1767225600
header roundtrip: TrueInside the snippet
All of the logic lives in the functions b64url_encode and b64url_decode.
Points of care
base64must be installed first — the snippet imports it directly.
Using it
The primary signature is def b64url_encode(data: bytes) -> str
The demo output is labeled (token:, decoded payload:, header roundtrip:), so every printed line maps back to its originating operation.
Import b64url_encode from the file and call it — the rest of the code is implementation detail.
Key statements
def b64url_decode(segment: str) -> bytes:
# 解码前按 len % 4 把填充补回来
return base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
def b64url_encode(data: bytes) -> str:
# 换成 URL 安全字母表,再去掉 '=' 填充
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Base64 Encoder & DecoderEncode text to Base64 and decode Base64 back to text with UTF-8 support. Handles Unicode characters correctly using TextEncoder and TextDecoder APIs.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `base64`, `json`. The file defines `b64url_encode`, `b64url_decode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.