PowerShell调用ADP API获取access token报客户端凭证无效求助
问题根因
- 核心错误是请求格式与声明的Content-Type不匹配:你指定了
ContentType 'application/x-www-form-urlencoded',但实际Body是经过ConvertTo-Json生成的JSON字符串,服务端无法从表单格式中解析到client_id、client_secret参数,因此返回凭证无效错误。 - 次要问题:
grant_type参数放在URL查询串中不符合OAuth2客户端模式的通用规范,部分接口实现会要求所有认证参数都放在请求Body内。 - 潜在风险:证书筛选逻辑未限制返回数量,若存在多张匹配
CN=CertCN*的证书,会传入证书数组导致请求异常。
修正后代码
$URLTokenV2="https://accounts.adp.com/auth/oauth/v2/token" # 表单参数不需要转JSON,直接传哈希表PowerShell会自动编码为x-www-form-urlencoded格式 $Body = @{ grant_type = 'client_credentials' client_id='xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx' client_secret='xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxxx' } # 证书筛选取第一个匹配结果避免异常 $Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object {$_.Subject -like "CN=CertCN*"} | Select-Object -First 1 $Response=Invoke-RestMethod -Uri $URLTokenV2 -Method Post -Body $Body -Certificate $Cert -ContentType 'application/x-www-form-urlencoded'
内容的提问来源于stack exchange,提问作者Kenny
相关产品推荐
相关产品推荐

