
使用 Microsoft Graph API 为 Azure 应用程序添加密码(secret)时,若通过 json= 参数传递已序列化的 JSON 字符串(而非原生字典),会导致 startDateTime 和 endDateTime 被静默忽略,API 回退至默认策略(2 年有效期)。根本原因在于 requests.post(..., json=...) 自动序列化,重复序列化将破坏请求体结构。
使用 microsoft graph api 为 azure 应用程序添加密码(secret)时,若通过 `json=` 参数传递已序列化的 json 字符串(而非原生字典),会导致 `startdatetime` 和 `enddatetime` 被静默忽略,api 回退至默认策略(2 年有效期)。根本原因在于 `requests.post(..., json=...)` 自动序列化,重复序列化将破坏请求体结构。
在调用 Microsoft Graph API 的 /applications/{id}/addPassword 端点时,自定义密钥有效期(如 60 天)失效是一个典型且隐蔽的问题。问题并非出在日期格式或时区处理上——您使用的 datetime.now(timezone.utc) 和 strftime('%Y-%m-%dT%H:%M:%S.%fZ') 完全符合 ISO 8601 标准,也满足 Graph API 对 startDateTime/endDateTime 的格式要求。
真正的问题在于请求负载(payload)的构造方式:
当您执行:
payload = json.dumps({"passwordCredential": {...}})
response = requests.post(..., json=payload)您实际上向 requests.post 的 json= 参数传入了一个字符串。而 requests 库的 json= 参数设计用于接收Python 原生对象(如 dict、list),它会在内部自动调用 json.dumps() 并设置正确的 Content-Type: application/json 头。若传入已是字符串,则 requests 会跳过序列化步骤,但此时 HTTP 请求体可能因双重编码或类型不匹配被 Graph API 解析失败——API 无法识别 passwordCredential 字段,于是完全忽略自定义时间字段,降级采用默认策略:startDateTime = now,endDateTime = now + 2 years。
✅ 正确做法是直接传入 Python 字典,交由 requests 完成序列化:
from datetime import datetime, timedelta, timezone
import requests
start_date = datetime.now(timezone.utc)
end_date = start_date + timedelta(days=60)
# ✅ 正确:ISO 8601 格式(注意 .%fZ 保留微秒并显式加 'Z')
start_date_str = start_date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')[:-3] + 'Z' # 可选:截断多余微秒位数(Graph 接受最多3位)
end_date_str = end_date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')[:-3] + 'Z'
payload = {
"passwordCredential": {
"displayName": "KeyRenewal",
"startDateTime": start_date_str,
"endDateTime": end_date_str
}
}
response = requests.post(
url=f"https://graph.microsoft.com/v1.0/applications/{application_id}/addPassword",
headers={"Authorization": f"Bearer {access_token}"},
json=payload # ← 这里传 dict,不是 json.dumps() 后的 str!
)⚠️ 关键注意事项:
- 不要手动调用
json.dumps()当使用json=参数; - 确保
startDateTime≤endDateTime(Graph 会校验,否则返回 400); - Graph API 实际接受的 ISO 格式支持毫秒级精度(
.fffZ),但不强制要求微秒;使用[:-3] + 'Z'可标准化为.000Z~.999Z,提升兼容性; - 若仍失效,请检查响应体中的
error字段(即使状态码为 200,部分 Graph 端点在字段无效时可能静默忽略);建议始终验证response.json().get('passwordCredential', {}).get('endDateTime')是否与预期一致; -
addPassword是针对 Application 对象 的操作(需 Application.ReadWrite.All 权限),确保服务主体(Service Principal)拥有对应权限且 consent 已完成。
总结:Graph API 对请求体结构极为敏感。保持 payload 为原生字典、信任 requests 的 json= 参数完成序列化,是确保自定义时间字段生效的前提。这一原则同样适用于所有 Graph REST 写操作(如 update, create),值得纳入团队 API 开发规范。

















