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

如何通过编程获取Azure API Management报表API的Bearer Token?

解决Azure APIM报表API编程获取有效Bearer Token的方法

核心前提

你调用的是Azure Resource Manager(ARM)类API,必须确保获取的Token满足两个关键条件:

  1. 令牌的**受众(audience)**为https://management.azure.com/
  2. 用于获取令牌的身份(应用或用户)拥有目标APIM实例的API Management Service Reader或更高权限(如Contributor)

可行的自动获取Token方案

方案1:服务主体(Server端自动化推荐)

这是服务器端无人值守场景的最优解,步骤如下:

  1. 在Azure AD中注册应用(服务主体),记录三个核心信息:
    • 客户端ID(client-id)
    • 客户端密钥(client-secret)
    • 租户ID(tenant-id)
  2. 给该服务主体在目标APIM实例的资源组或APIM资源上分配API Management Service Reader角色
  3. 通过以下HTTP请求获取Token:
    POST https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=client_credentials
    &client_id={client-id}
    &client_secret={client-secret}
    &scope=https://management.azure.com/.default
    
  4. 将返回结果中的access_token作为Bearer Token放入请求头,调用APIM报表API

方案2:用户身份模拟(本地调试场景)

如果需要模拟用户操作(比如本地开发调试),可以使用设备码流程:

  1. 在Azure AD注册应用时,启用"设备码"授权流
  2. 先请求设备码:
    POST https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/devicecode
    Content-Type: application/x-www-form-urlencoded
    
    client_id={client-id}
    &scope=https://management.azure.com/user_impersonation offline_access
    
  3. 按照返回提示,在浏览器打开指定URL输入验证码,完成用户登录验证
  4. 轮询获取Token:
    POST https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=urn:ietf:params:oauth:grant-type:device_code
    &client_id={client-id}
    &device_code={返回的device_code}
    
  5. 使用返回的access_token调用目标API

常见问题排查

  • Token受众错误:解码Token确认aud字段是否为https://management.azure.com/,若为其他值,说明请求的scope参数配置错误
  • 权限不足:通过Azure门户的"访问控制(IAM)"页面,验证身份是否拥有APIM资源的读取权限
  • 路径/版本错误:确认请求路径中的{subscriptionId}、{resourceGroupName}、{serviceName}替换正确,API版本2022-08-01与文档要求一致

内容的提问来源于stack exchange,提问作者pit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:34:54