[Python] Failed to call api `https://mdmenrollment.apple.com/server/devices` use python3

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to use python3 to call apple api, and it failed, the api document is https://developer.apple.com/documentation/devicemanagement/fetch-devices

    I suppose that I use the wrong aud in jwt declaration, but the document almost has no explation. https://developer.apple.com/documentation/appstoreconnectapi/generating-tokens-for-api-requests. My test code is below. Thanks.

    from datetime import datetime, timedelta
    from time import time, mktime
    import jwt
    import requests

    key_id="xxxxxxxxx"
    issuer_id="xxxxxxxxxxx"
    private_key_path = "./xxxxxxxxxxxxx.p8"

    dt = datetime.now() + timedelta(minutes=19)

    headers = {
    "alg": "ES256",
    "kid": key_id,
    "typ": "JWT",
    }

    payload = {
    "iss": issuer_id,
    "iat": int(time()),
    "exp": int(mktime(dt.timetuple())),
    "aud": "apple-developer-enterprise-v1",
    }

    with open(private_key_path, "rb") as fh:
    signing_key = fh.read()

    gen_jwt = jwt.encode(payload, signing_key, algorithm="ES256", headers=headers)

    headers = {
    "Authorization": f"Bearer {gen_jwt}",
    "Content-Type": "application/json",
    "Accept": "application/json"
    }

    url = f"https://mdmenrollment.apple.com/server/devices"

    payload = {
    "limit": 1000
    }

    response = requests.post(url, headers=headers, json=payload)
    print(f"响应状态码: {response.status_code}")
    print(f"payload: {payload}")
    print(f"响应头: {response.headers}")
    print(f"响应内容: {response.text}")
    response.raise_for_status()
    print("aa11-------------", response.json())



    And error is

    401 Client Error: Unauthorized for url: https://mdmenrollment.apple.com/server/devices

    Continue reading...

Compartilhe esta Página