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

Azure函数中使用托管标识通过Microsoft.Graph访问Graph API报错如何解决

问题根因

你当前使用的Connect-MgGraph默认触发交互式认证逻辑,Azure Functions无交互运行环境不支持该模式,自动降级到DeviceCode认证时需要写入本地认证缓存文件,触发了路径不存在的报错。

解决方案

核心代码调整

直接在Connect-MgGraph中指定使用托管标识认证即可,根据你使用的托管标识类型选择对应代码:

系统分配托管标识(你当前的配置场景)

Import-Module Microsoft.Graph.Authentication
# 直接指定使用托管标识认证,应用权限场景Scope固定为 Graph 默认端点
Connect-MgGraph -Identity -Scopes 'https://graph.microsoft.com/.default'

$reportJson = Invoke-GraphRequest -Uri 'https://graph.microsoft.com/beta/reports/credentialUserRegistrationDetails?$top=5000' -Method GET

用户分配托管标识(可选场景)

如果后续切换为用户分配托管标识,额外传入对应托管标识的客户端ID即可:

Connect-MgGraph -Identity -ClientId "<你分配的托管标识客户端ID>" -Scopes 'https://graph.microsoft.com/.default'

必要校验项

  • 确认已为托管标识分配Microsoft Graph的应用权限(而非委托权限),且已完成管理员同意
  • 确认函数站点的requirements.psd1文件中已指定Microsoft.Graph.Authentication模块的版本,建议使用2.x以上稳定版避免兼容问题,示例配置:
# requirements.psd1 内容
@{
    'Microsoft.Graph.Authentication' = '2.*'
}

调整后重新部署函数即可正常运行,不需要额外存储任何敏感凭据。

内容的提问来源于stack exchange,提问作者Raymond A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:15:01