
Azure OpenAI REST API 调用返回 401 错误,根本原因是混淆了 Azure AD Token 与 API Key 的认证头格式——使用 API Key 时必须用 api-key 请求头,而非 Authorization: Bearer 。
azure openai rest api 调用返回 401 错误,根本原因是混淆了 azure ad token 与 api key 的认证头格式——使用 api key 时必须用 `api-key` 请求头,而非 `authorization: bearer
在 Azure OpenAI 服务中,存在两种主流身份验证方式:基于 Azure Active Directory(AAD)的 OAuth 2.0 Token 认证 和 基于资源级 API Key 的简单密钥认证。二者不可混用,且请求头(Header)格式完全不同:
-
✅ API Key 方式(推荐用于快速开发与脚本调用):
使用 Azure Portal 或 Azure CLI 获取的 API Key(共两个,可轮换),必须通过 api-key 请求头传递:api-key: <your-api-key-here></your-api-key-here>
-
❌ 错误写法(常见误区):
将 API Key 当作 Bearer Token 放入 Authorization 头:Authorization: Bearer <your-api-key-here> // ❌ 错误!这仅适用于 AAD Token</your-api-key-here>
此时 Azure 会校验 Token 的签名、签发者(issuer)、受众(audience,如 https://cognitiveservices.azure.com)及有效期——而纯 API Key 并非合法 JWT,必然触发 Unauthorized. Access token is missing, invalid, audience is incorrect... 错误。
✅ 正确的 Python 示例代码(API Key 模式)
import requests
# ✅ 确保从 Azure Portal 的「Keys and Endpoint」页复制正确的 API Key(Key 1 或 Key 2)
API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # 替换为你的实际 key
ENDPOINT = "https://xxx.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-02-15-preview"
payload = {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me a joke."}
],
"temperature": 0.7,
"max_tokens": 100
}
# ✅ 关键修正:使用 'api-key' 头,而非 'Authorization'
headers = {
"Content-Type": "application/json",
"api-key": API_KEY # ⚠️ 注意:无 'Bearer' 前缀,值即为原始 key 字符串
}
response = requests.post(ENDPOINT, headers=headers, json=payload)
if response.status_code == 200:
print("✅ Success:", response.json()["choices"][0]["message"]["content"])
else:
print(f"❌ Error {response.status_code}: {response.text}")
? 补充排查要点
- Endpoint URL 必须完整且正确:确保包含 /openai/... 路径及 ?api-version=... 查询参数;Azure OpenAI 的 endpoint 不支持 通用 https://cognitiveservices.azure.com 根域名。
- API Key 权限与状态:确认该 key 未过期、未被禁用,且所属资源处于运行状态(非已删除或暂停)。
- 区域与模型部署匹配:示例中模型 gpt-4o 部署在 swedencentral 区域,Endpoint 中的子域名(如 xxx.openai.azure.com)必须对应同一区域资源。
- 免费试用限制:API Key 认证与订阅层级无关,免费试用额度内完全可用;401 错误与配额耗尽(返回 429)或权限不足(403)有本质区别,请勿混淆。
? 提示:若后续需集成企业单点登录(SSO)或更细粒度 RBAC 控制,可切换至 Azure AD 认证模式——此时才需使用 Authorization: Bearer
,并通过 Microsoft Identity Platform 获取有效 Token,且 audience 必须设为 https://cognitiveservices.azure.com。但对绝大多数应用集成场景,API Key 方式更简洁可靠。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











