Powershell ADP API 令牌

问题描述

我在 Powershell 中运行以下程序。我收到一条错误消息,指出“给定的客户端凭据无效”。我正在尝试执行使用 API 的第一步,即生成访问令牌。我已确认我拥有有效的 client_id 和 client_secret。

这在 Postman 中有效,但我在 Powershell 中没有看到我有什么问题。帮助!

$URLTokenV2="https://accounts.adp.com/auth/oauth/v2/token?grant_type=client_credentials"
$Json= @{
    client_id='xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'
    client_secret='xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxxx'
}
$Json=$Json | ConvertTo-Json
$Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object {$_.Subject -like "CN=CertCN*"}
$Response=Invoke-RestMethod -Uri $URLTokenV2 -Method Post -Body $Json -Certificate $Cert -ContentType 'application/x-www-form-urlencoded'

我已经对 Invoke-RestMethod 和 Invoke-WebRequest 进行了相同的尝试。我得到了相同的结果,即客户端凭据无效。

感谢回复。提前致谢。

解决方法

来自ADP's public documentation

一般来说,您的消费者应用程序应该传递 client_id 和 使用 HTTP 授权标头中的 client_secret 参数 HTTP 基本身份验证方案(或其他指定方案)。这 client_id 和 client_secret 必须用单个冒号 (":") 分隔 字符并根据需要在 base64 编码字符串中进行编码 IETF RFC 2617。

您的消费者应用程序必须:

  • 使用注册期间提供的 X.509 证书发送请求。
  • 使用 HTTP 标头 Content-Type 指定的 UTF-8 字符编码以 URL 编码格式传递所有参数: 应用程序/x-www-form-urlencoded。实际请求可能看起来像 以下示例:
 POST /auth/oauth/v2/token HTTP/1.1
 Host: accounts.adp.com
 Authorization: Basic QURQVGFibGV0OnRoZXRhYmxldHBhc3N3b3Jk
 Content-Type: application/x-www-form-urlencoded
 grant_type=client_credentials

所以你需要做这样的事情:

$URLTokenV2 = 'https://accounts.adp.com/auth/oauth/v2/token'

# Prepare Basic Authentication header payload (the base64 part)
$AuthorizationValue = [Convert]::ToBase64String(
  [System.Text.Encoding]::UTF8.GetBytes('xxxxxxxxx-client-id-xxxxxxxxx:xxxxxx-client-secret-xxxxxxxxxxxx')
)

$Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object {$_.Subject -like "CN=CertCN*"}

# Prepare request body - no need to explicitly convert to JSON 
$Body = @{
  grant_type = 'client_credentials'
}

# Pass the `Authorization` header value with the payload we calculate from the id + secret
$Response = Invoke-RestMethod -Uri $URLTokenV2 -Method Post -Header @{ Authorization = "Basic ${AuthorizationValue}" } -Body $Body -Certificate $Cert -ContentType 'application/x-www-form-urlencoded'
,

根据 Mathias 的评论,我现在有以下工作

$URLTokenV2="https://accounts.adp.com/auth/oauth/v2/token?"
$Json= @{
     client_id='xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'
     client_secret='xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxxx'
     grant_type='client_credentials'
}
$Response=Invoke-RestMethod -Uri $URLTokenV2 -Method Post -Body $Json -Certificate $Cert -ContentType 'application/x-www-form-urlencoded'

我曾尝试将“grant_type='client_credentials'”作为 Json 数组的一部分,但这次尝试时我不小心留下了 '?'在网址中。我还必须删除转换为 Json 的行。之后就成功了。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...