← 中文资源

简体中文版本

Base64url 编码 JWT 分段

urlsafe_b64encode 去掉 = 填充就是 JWT 的分段编码;解码前按 len % 4 补回填充,头段与载荷段都能无损还原成原始字节。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzQyIiwiZXhwIjoxNzY3MjI1NjAwfQ.ZGVtby1zaWduYXR1cmUtYnl0ZXM
decoded payload: user_42 1767225600
header roundtrip: True

实现说明

除了函数 b64url_encode、b64url_decode,文件里再无其他定义。

使用要点

  • 跑完文件,输出里会留下标记——token:、decoded payload:、header roundtrip:。
  • b64url_encode 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 全部导入都来自标准库:base64、json。 文件在加载时定义 b64url_encode、b64url_decode。

入口签名:def b64url_encode(data: bytes) -> str

核心语句

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")

代码示例

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"}')