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

调用Apple设备管理API返回401 Unauthorized错误的排查求助

调用Apple设备管理API返回401 Unauthorized错误的排查求助

大家好,我最近在用Python 3调用Apple的设备管理API(Fetch Devices接口)时一直遇到401 Unauthorized错误,折腾了好半天没搞定,想请各位帮忙看看问题出在哪。

我猜测问题可能出在JWT声明里的aud参数上,但翻了官方文档,关于这个参数的说明几乎没什么有用的信息,只找到了生成API请求令牌的相关文档参考,还是没搞清楚正确的aud值应该填什么。

以下是我的测试代码:

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

运行后得到的错误信息是:

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

我已经检查过这些点,但还是没解决问题:

  • JWT的iss是正确的Issuer ID,kid也和我的私钥ID对应,过期时间设置为19分钟后,符合Apple的要求(不超过20分钟)
  • 私钥文件路径正确,读取过程没有报错,JWT生成也正常
  • 请求头的格式没问题,Authorization用了Bearer前缀,Content-Type和Accept都设置为application/json,请求方式和URL也和文档一致

现在主要疑惑的点就是:

  • 我填的aud值apple-developer-enterprise-v1是否正确?有没有用过这个设备管理API的朋友能告诉我正确的aud取值?
  • 还有没有其他可能导致401错误的地方我没考虑到?

麻烦各位大佬帮忙指点一下,谢谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:49:31