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

Azure Log Analytics API授权认证求助:是否支持客户端凭据及示例

Azure Log Analytics API 客户端凭据认证支持及示例

支持情况

Azure Log Analytics API 完全支持客户端凭据认证,这种认证方式适用于服务对服务的后台调用场景,无需用户交互,是官方推荐的非交互式认证方案。

认证示例

1. PowerShell 示例

需先在Azure AD中注册应用,获取以下信息:Tenant ID、Client ID(应用ID)、Client Secret(应用密钥)、Log Analytics工作区的Workspace ID。

# 定义参数
$tenantId = "<你的租户ID>"
$clientId = "<你的应用ID>"
$clientSecret = "<你的应用密钥>"
$workspaceId = "<你的Log Analytics工作区ID>"
$resource = "https://api.loganalytics.io"

# 获取访问令牌
$tokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
    resource      = $resource
}
$tokenResponse = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $body

# 调用Log Analytics API(示例:查询最近24小时的日志)
$apiUri = "https://api.loganalytics.io/v1/workspaces/$workspaceId/query"
$queryBody = @{
    query = "AzureActivity | where TimeGenerated > ago(24h) | take 10"
} | ConvertTo-Json

$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-Type"  = "application/json"
}

$apiResponse = Invoke-RestMethod -Uri $apiUri -Method Post -Headers $headers -Body $queryBody
$apiResponse

2. Python 示例

使用requests库实现,需提前准备好租户ID、应用ID、应用密钥和工作区ID:

import requests
import json

# 配置参数
tenant_id = "<你的租户ID>"
client_id = "<你的应用ID>"
client_secret = "<你的应用密钥>"
workspace_id = "<你的Log Analytics工作区ID>"
resource = "https://api.loganalytics.io"

# 获取访问令牌
token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token"
token_payload = {
    "grant_type": "client_credentials",
    "client_id": client_id,
    "client_secret": client_secret,
    "resource": resource
}
token_response = requests.post(token_url, data=token_payload)
token_response.raise_for_status()
access_token = token_response.json()["access_token"]

# 调用Log Analytics API
api_url = f"https://api.loganalytics.io/v1/workspaces/{workspace_id}/query"
query_payload = {
    "query": "AzureActivity | where TimeGenerated > ago(24h) | take 10"
}
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

api_response = requests.post(api_url, headers=headers, json=query_payload)
api_response.raise_for_status()
print(json.dumps(api_response.json(), indent=2))

注意事项

  • 确保注册的Azure AD应用已被授予Log Analytics工作区的相应权限(如Log Analytics Reader或Log Analytics Contributor角色),否则会触发权限不足错误。
  • 应用密钥需妥善保管,避免泄露;也可使用证书代替密钥认证,安全性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:11