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

如何用Python实现JWT RS256算法及解决encode方法不存在错误

Python中基于RS256算法构建JWT及常见问题解决

解决AttributeError: module 'jwt' has no attribute 'encode'错误

  • 核心原因:你安装的jwt包并非主流维护的PyJWT库,这个旧包功能残缺且已停止更新,不存在encode方法。
  • 修复步骤:
    1. 卸载错误依赖:
      pip uninstall -y jwt
      
    2. 安装正确的支持库:
      pip install pyjwt cryptography
      
      注:cryptography用于支持RS256这类非对称加密算法,必须安装
    3. 优化后的代码(修复文件读取逻辑,避免资源泄漏):
      import jwt
      from datetime import datetime, timedelta
      
      # 用with语句安全读取私钥文件
      with open("C:\\file\\privateKey.pem", "r") as f:
          private_key = f.read()
      
      payload = {
          "iss": "iss",
          "aud": "aud",
          "scope": "*",
          "iat": int(datetime.now().timestamp()),  # 用当前时间生成时间戳更灵活
          "exp": int((datetime.now() + timedelta(hours=24)).timestamp())
      }
      
      signed_jwt = jwt.encode(payload, private_key, algorithm='RS256')
      print(signed_jwt)
      

基于RS256算法构建JWT的完整步骤

RS256是基于RSA的SHA-256非对称加密算法,需用私钥签名、公钥验证,适合分布式场景下的身份认证。

  1. 安装依赖
    执行命令安装必需库:

    pip install pyjwt cryptography
    
  2. 准备RSA私钥
    可以通过OpenSSL生成PEM格式的2048位RSA私钥:

    openssl genrsa -out privateKey.pem 2048
    
  3. 构造JWT Payload
    Payload包含业务声明信息,常见字段:

    • iss:令牌签发者
    • aud:令牌接收方
    • iat:令牌签发时间(Unix时间戳)
    • exp:令牌过期时间(Unix时间戳)
    • 自定义字段(如权限范围scope)
  4. 生成签名后的JWT
    使用PyJWT的jwt.encode()方法完成签名:

    import jwt
    from datetime import datetime, timedelta
    
    with open("privateKey.pem", "r") as f:
        private_key = f.read()
    
    payload = {
        "iss": "your-service-id",
        "aud": "target-api-domain",
        "scope": "read:data write:data",
        "iat": int(datetime.now().timestamp()),
        "exp": int((datetime.now() + timedelta(hours=1)).timestamp())  # 设置1小时有效期
    }
    
    jwt_token = jwt.encode(payload, private_key, algorithm='RS256')
    print(jwt_token)
    
  5. 验证JWT(可选)
    用对应公钥验证令牌合法性:

    # 先从私钥导出公钥:openssl rsa -in privateKey.pem -pubout -out publicKey.pem
    with open("publicKey.pem", "r") as f:
        public_key = f.read()
    
    try:
        decoded_payload = jwt.decode(
            jwt_token,
            public_key,
            algorithms=['RS256'],
            audience="target-api-domain"  # 验证受众匹配
        )
        print("令牌验证通过:", decoded_payload)
    except jwt.InvalidTokenError:
        print("无效的JWT令牌")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:30:31