Powershell ADP API 令牌

Powershell ADP API Token

我是运行下面的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

In general, your consumer application should pass the client_id and client_secret parameters in the HTTP Authorization header using the HTTP Basic authentication scheme (or other designated scheme). The client_id and client_secret must be separated by a single colon (":") character and encoded within a base64-encoded string, as required by IETF RFC 2617.

Your consumer application must:

  • Send the request with the X.509 certificate provided during registration.
  • Pass all parameters in a URL-encoded format with UTF-8 character encoding as specified by the HTTP header Content-Type: application/x-www-form-urlencoded. The actual request might look like the following example:
 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 数组的一部分,但这次尝试时不小心遗漏了 '?'在 URL。我还必须删除到 convertto-Json 的行。之后就成功了。