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

使用MSAL Python库创建Azure活动日志告警遇权限错误求助

解决Azure活动日志告警创建的AuthorizationFailed错误

问题场景

使用MSAL Python库创建Azure活动日志告警时触发权限错误,代码及错误详情如下:

执行代码

from azure.identity import ClientSecretCredential
from azure.mgmt.monitor import MonitorManagementClient

MSAL_CLIENT_ID = "<My Client Id>" 
MSAL_CLIENT_SECRET = "<My Client Secret>"
TENANT_ID = "<My Tenant Id>"

credentials = ClientSecretCredential(
    client_id = MSAL_CLIENT_ID,
    client_secret = MSAL_CLIENT_SECRET,
    tenant_id = TENANT_ID
)

SUBSCRIPTION_ID = "<My Subscription Id>"
monitor_client = MonitorManagementClient(
    credential=credentials,
    subscription_id=SUBSCRIPTION_ID
)

GROUP_NAME = "<My Resource Group Name>"
ACTIVITY_LOG_ALERT_NAME = "test"

log_alert = monitor_client.activity_log_alerts.create_or_update(
    GROUP_NAME,
    ACTIVITY_LOG_ALERT_NAME,
    {
      "location": "Global",
      "scopes": [
        "subscriptions/" + SUBSCRIPTION_ID
      ],
      "enabled": True,
      "condition": {
        "all_of": [
          {
            "field": "category",
            "equals": "Administrative"
          },
          {
            "field": "level",
            "equals": "Error"
          }
        ]
      },
      "actions": {
        "action_groups": [
        ]
      },
      "description": "Sample activity log alert description"
    }
)
print("Create activity log alert:\n{}".format(log_alert))

错误信息

HttpResponseError: (AuthorizationFailed) The client '17abcd' with object id '17abcd' does not have authorization to perform action 'Microsoft.Insights/activityLogAlerts/write' over scope '/subscriptions/59abcd/resourceGroups/MyResource/providers/Microsoft.Insights/activityLogAlerts/test' or the scope is invalid. If access was recently granted, please refresh your credentials.
Code: AuthorizationFailed
Message: The client '17abcd'' with object id '17abcd'' does not have authorization to perform action 'Microsoft.Insights/activityLogAlerts/write' over scope '/subscriptions/59abcd/resourceGroups/MyResource/providers/Microsoft.Insights/activityLogAlerts/test' or the scope is invalid. If access was recently granted, please refresh your credentials.

解决步骤

  • 配置服务主体权限:在Azure门户中,找到目标订阅或资源组的**访问控制(IAM)页面,为代码中使用的服务主体(对应MSAL_CLIENT_ID的应用)添加监控参与者(Monitoring Contributor)**角色,该角色包含创建活动日志告警所需的Microsoft.Insights/activityLogAlerts/write权限;也可创建自定义角色,仅包含所需权限以遵循最小权限原则。
  • 验证作用域参数:确认代码中的SUBSCRIPTION_ID、GROUP_NAME与Azure门户中的实际资源信息一致,确保目标资源组存在于指定订阅下。
  • 等待权限生效:新分配的Azure RBAC权限通常需要5-10分钟同步,若刚添加权限,等待后重新运行代码即可,无需手动刷新凭据,ClientSecretCredential会自动获取最新访问令牌。
  • 更新SDK版本:确保azure-mgmt-monitor包为最新版本,执行pip install --upgrade azure-mgmt-monitor更新,避免因SDK版本兼容问题导致的权限验证异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:15:41