首页 > 解决方案 > 如何生成苹果授权令牌/客户端密码?

问题描述

如何在 python 中为苹果登录和设备检查生成授权码/客户端密码?

标签: pythonjwtapple-sign-indevicecheck

解决方案


  1. 首先,我们需要生成一个特定于应用程序的 p8 文件(pem 格式的私钥)为此执行以下操作:
  • 转到您的苹果开发者门户,在证书标识符和配置文件苹果 => 密钥下
  • 单击 + 号并使用您要使用的服务创建一个密钥
  • 然后下载p8文件(注意不要丢失,不能再次下载)
  • 还复制您稍后需要的密钥ID
  1. 在 python 中安装 pyjwt 并执行以下操作:
  • 创建一个有效载荷字典:
         
data = {
    "iss": "team_id", # team id of your developer account this can be found in your apple developer portal => identifier of your app => "App ID prefix"
    "iat": timestamp_now, # creation timestamp in seconds
    "exp": timestamp_exp, # expiration timestamp in seconds (max 20 mins) see 
    "aud": "https://appleid.apple.com",
    "sub": client_id # your bundle
}

  • 打开并将私钥(您在步骤 1 中下载的)读入变量
with open("filename.p8", "r") as f:
    private_key = f.read()
  • 生成签名的 jwt 令牌:
token = jwt.encode(payload=data, key=private_key, algorithm="ES256", headers={
    "kid":key_id # the key id is the id u saved in step 1
}).decode()
  • jwt.encode 如果您希望它作为一个字符串返回字节,您需要像我一样对其进行解码

完整的代码将如下所示

import jwt

def generate_token()
        with open("filename.p8", "r") as f:
            private_key = f.read()
        team_id = "teamid"
        client_id = "bundle.id"
        key_id = "keyid"
        validity_minutes = 20
        timestamp_now = int(utils.time_stamp_seconds())
        timestamp_exp = timestamp_now + (60 * validity_minutes)
        cls.last_token_expiration = timestamp_exp
        data = {
                "iss": team_id,
                "iat": timestamp_now,
                "exp": timestamp_exp,
                "aud": "https://appleid.apple.com",
                "sub": client_id
            }
        token = jwt.encode(payload=data, key=private_key, algorithm="ES256", headers={"kid": key_id}).decode()

推荐阅读