Base64url Encodes JWT Segments Without Padding

urlsafe_b64encode with the '=' padding stripped produces JWT-style segments, and decode restores the missing padding before decoding.

PythonAuth Jwt

Code

pythonsnippet
23 lines
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: True

Inside the snippet

All of the logic lives in the functions b64url_encode and b64url_decode.

Points of care

  • base64 must 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

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.