You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中不安装额外第三方包实现JWT解码

Python3 无第三方依赖JWT访问令牌解码实现

实现原理

  • JWT令牌本质是由.分割的3段Base64URL编码内容,顺序为头部.载荷.签名,仅做解码不验签的场景下,仅需处理前两段内容即可
  • Python标准库内置base64、json模块足够支撑解码需求,仅需要额外处理Base64URL和标准Base64的格式差异:
    • Base64URL会把标准Base64的+替换为-、/替换为_
    • Base64URL会省略末尾填充的=字符,解码前需要补全到长度为4的倍数

完整代码实现

import base64
import json

def decode_jwt(token: str) -> dict:
    def fix_base64_padding(encoded_str: str) -> str:
        # 补全Base64填充字符
        padding_needed = 4 - len(encoded_str) % 4
        if padding_needed:
            encoded_str += "=" * padding_needed
        return encoded_str
    
    # 拆分JWT三段内容
    parts = token.split(".")
    if len(parts) != 3:
        raise ValueError("无效的JWT令牌格式")
    
    # 解码头部
    header_b64 = fix_base64_padding(parts[0].replace("-", "+").replace("_", "/"))
    header = json.loads(base64.b64decode(header_b64).decode("utf-8"))
    
    # 解码载荷
    payload_b64 = fix_base64_padding(parts[1].replace("-", "+").replace("_", "/"))
    payload = json.loads(base64.b64decode(payload_b64).decode("utf-8"))
    
    return {
        "header": header,
        "payload": payload
    }

使用示例

# 替换为你的JWT令牌
your_jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
result = decode_jwt(your_jwt_token)
print("JWT头部:", json.dumps(result["header"], indent=2, ensure_ascii=False))
print("JWT载荷:", json.dumps(result["payload"], indent=2, ensure_ascii=False))

注意:该实现仅做解码操作,不包含签名验证逻辑,生产环境如果需要校验令牌合法性,建议额外补充验签逻辑。

内容的提问来源于stack exchange,提问作者silent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:15:01