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

PowerShell中OAuth 2.0调用API遇认证失败问题求助

OAuth 2.0自动化生成Bearer Token问题排查

现状

目前只能通过Swagger授权界面手动勾选权限范围后生成Bearer Token,复制到PowerShell脚本中执行API调用才能正常工作,希望实现Token的自动化生成,无需手动操作。

已完成工作

已获取API的client_id、tenantID、client_secret、scope、redirect_url等信息,编写PowerShell脚本通过客户端凭证流(client_credentials)成功获取Token,但使用该Token调用API时返回错误:"Not authenticated!"

脚本内容如下:

Connect-AzAccount 

# 收集所有租户
$allTenants = Get-AzTenant

# 筛选目标租户
$targetTenant = $allTenants | Where-Object { $_.Name -eq "XXX" }

# 检查是否找到租户
if ($targetTenant -ne $null) {
    $tenantName = $targetTenant.Name
    $tenantId = $targetTenant.Id
    #Write-Output "Der Tenant mit dem Namen '$tenantName' hat die ID '$tenantId'."
} else {
    #Write-Output "Der Tenant mit dem Namen 'XXX' wurde nicht gefunden."
}

$TokenEndpoint = "https://login.microsoftonline.com/"+$tenantId+"/oauth2/v2.0/token"

$BodyBearer = @{
    grant_type="client_credentials"
    client_id="XXX..."
    client_secret="XXX..."
    scope="api://XXX.../.default"
}

$TokenResponse = Invoke-RestMethod -Uri $TokenEndpoint -Body $BodyBearer -Method Post 
$token = $TokenResponse.access_token

尝试的其他方法

推测需分两步完成认证:1. 通过https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize进行认证;2. 通过Token端点生成Bearer Token。于是尝试采用授权码流(Auth_code with PKCE):

  1. 通过授权链接获取code:
"https://login.microsoftonline.com/mytenant_id/oauth2/v2.0/authorize?
response_type=code& client_id=XXX&
redirect_uri=http://localhost:5000/docs/oauth2-redirect&
scope=api://XXX/XXX& code_challenge=XXX& code_challenge_method=S256"

获取到code:0.ATsAD_kXDqOIk0-l18yEfP8wfhy2yu-....

  1. 编写脚本用code请求Token:
$Body = @{
    # 指定使用授权码流
    grant_type   = 'authorization_code'
    client_id="XXX..."
    client_secret="XXX..."
    scope="api://XXX.../.default"
    # 上一步从浏览器获取的code
    code         = '0.ATs....'
    code_verifier = "XXX...." # 从code_challenge生成
}
try {
    $antwort = Invoke-RestMethod 'https://login.microsoftonline.com/tenant_id/oauth2/v2.0/token' -Method POST -Body $Body -ContenType 'application/x-www-form-urlencoded'
    
} catch {
    $textBoxOutput = "Error during API request: $_"
}
  • 携带client_secret时返回错误:
Error during API request: {"error":"invalid_client","error_description":"AADSTS700025: Client is public so neither 'client_assertion' nor 'client_secret' should be presented.
  • 移除client_secret后返回错误:
Error during API request: {"error":"invalid_request","error_description":"AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests.

求助

已尝试多种认证方式但未解决问题,恳请协助排查错误原因并提供可行的解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:28:22