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

Arc已连接本地VM通过REST API获取Access Token报错求助

Azure Arc连接VM获取Token时Runtime Error的解决方法

先确认IDENTITY_ENDPOINT环境变量是否正常

首先检查本地VM里的IDENTITY_ENDPOINT环境变量是否正确配置:

$env:IDENTITY_ENDPOINT

正常返回应该是类似http://localhost:40342/metadata/identity/oauth2/token的地址。如果为空或者地址不对,说明Arc Agent的身份服务没正常启动,重启服务试试:

Restart-Service -Name "AzureConnectedMachineAgent"

修正URL编码问题

官方文档里的代码没对resource参数做URL编码,这会导致请求解析出错。修改endpoint的构造逻辑,对资源URI编码:

$apiVersion = "2020-06-01"
$resource = "https://management.azure.com/"
# 对resource参数做URL编码
$encodedResource = [Uri]::EscapeDataString($resource)
$endpoint = "{0}?resource={1}&api-version={2}" -f $env:IDENTITY_ENDPOINT, $encodedResource, $apiVersion

使用带错误捕获的完整请求流程

如果环境变量没问题,换下面的代码试试,它能捕获更详细的错误信息:

$apiVersion = "2020-06-01"
$resource = "https://management.azure.com/"
$encodedResource = [Uri]::EscapeDataString($resource)
$endpoint = "{0}?resource={1}&api-version={2}" -f $env:IDENTITY_ENDPOINT, $encodedResource, $apiVersion
$secretFile = ""

try {
    $response = Invoke-WebRequest -Method GET -Uri $endpoint -Headers @{Metadata='True'} -UseBasicParsing -ErrorAction Stop
}
catch {
    $statusCode = $_.Exception.Response.StatusCode.value__
    Write-Host "请求错误状态码: $statusCode"
    if ($_.Exception.Response.Headers.ContainsKey("WWW-Authenticate")) {
        $wwwAuthHeader = $_.Exception.Response.Headers["WWW-Authenticate"]
        if ($wwwAuthHeader -match "Basic realm=.+") {
            $secretFile = ($wwwAuthHeader -split "Basic realm=")[1]
            Write-Host "密钥文件路径: $secretFile"
        }
    }
    Write-Host "错误详情: " $_.Exception.Message
}

if ($secretFile) {
    try {
        $secret = Get-Content -Path $secretFile -Raw -ErrorAction Stop
        $response = Invoke-WebRequest -Method GET -Uri $endpoint -Headers @{Metadata='True'; Authorization="Basic $secret"} -UseBasicParsing -ErrorAction Stop
        $token = (ConvertFrom-Json -InputObject $response.Content).access_token
        Write-Host "获取Token成功: " $token.Substring(0, 50) "..." # 只显示前50位防止泄露
    }
    catch {
        Write-Host "用密钥请求Token失败: " $_.Exception.Message
    }
}

更简单的替代方案:用Azure CLI获取Token

手动调用API容易踩坑,直接用Azure CLI更靠谱:

  1. 先在VM上安装Azure CLI:
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'
  1. 用Arc托管身份登录(不用手动输账号密码):
az login --identity --username <你的Arc托管身份客户端ID/资源ID>
  1. 获取目标资源的Token:
az account get-access-token --resource https://management.azure.com/

额外排查点

  • 确保Arc Agent是最新版本:旧版本可能有bug,执行更新:
azcmagent upgrade
  • 检查VM网络:确认本地http://localhost:40342端口没被防火墙拦截,且VM能正常访问Arc服务的网络端点。
  • 确认托管身份权限:在Azure门户的Arc机器页面,检查“身份”选项卡是否启用了托管身份,且该身份有访问目标资源(比如Key Vault)的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:37:15