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

已通过Connect-AzAccount登录Azure,如何用当前账户生成OAuth令牌?

解决方案

1. 更新Az模块到最新版本

旧版本Az模块可能存在共享令牌缓存的兼容性问题,先确保模块处于最新状态:

Update-Module -Name Az -Force -AllowClobber

更新完成后重启PowerShell会话再尝试操作。

2. 使用支持共享令牌缓存的方式登录

默认的Connect-AzAccount交互式登录可能未将令牌写入SharedTokenCache,改用设备验证码登录:

Connect-AzAccount -UseDeviceAuthentication

按照提示完成登录后,再执行令牌获取命令:

Get-AzAccessToken -ResourceUrl "api://83....."

3. 直接调用Azure CLI获取令牌(兼容方案)

既然已确认Azure CLI能生成有效令牌,可在PowerShell中直接调用并解析结果:

# 获取令牌并转换为JSON对象
$tokenResponse = az account get-access-token --resource "api://83....." | ConvertFrom-Json
# 提取访问令牌
$accessToken = $tokenResponse.accessToken

这种方式无需依赖Az模块的缓存,直接复用Azure CLI的登录状态。

4. 从Az上下文的令牌缓存中提取

如果上述方法仍不生效,可以直接从当前Az上下文的令牌缓存中读取:

# 获取当前Azure上下文
$azContext = Get-AzContext
# 读取缓存中的所有令牌
$cachedTokens = $azContext.TokenCache.ReadItems()
# 筛选目标资源的最新令牌
$targetToken = $cachedTokens | Where-Object { $_.Resource -eq "api://83....." } | Select-Object -Last 1
# 提取访问令牌
$accessToken = $targetToken.AccessToken

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:14:53