我在Powershell中有一个脚本,在其中我请求Bearer令牌以后再做一些事情。 问题是,我总是收到错误请求(400)
在正文中,我提供了clientId和ClientSecret,但看起来该呼叫未使用我的凭据
有人可以帮我吗?
我在互联网上进行了大量搜索,并尝试了一些不同的方法,但到目前为止没有任何效果。
function GetBearer ([string]$clientId, [string]$clientSecret) {
$tokenEndpoint = 'http://web-scsecur-sso.appliarmony.net/TokenService/connect/token'
$body = @{
'client_id'= $clientId
'grant_type' = 'client_credentials'
'client_secret' = $clientSecret
}
$params = @{
Body = $Body
Method = 'Post'
Uri = $tokenEndpoint
}
$token = Invoke-WebRequest -Uri "http://web-scsecur-sso.appliarmony.net/TokenService/connect/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
Return "Bearer " + ($token.access_token).ToString()
}
输出应为Bearer令牌,但到目前为止我什么都没收到。
答案 0 :(得分:1)
来自网络服务器的HTTP 400(错误请求)响应告诉您,它不喜欢您的请求,并且拒绝执行任何操作。可能有很多问题(身体参数中的错字,错误的网址,无效/过期的机密等)。
一些API在其400个响应中将更加详细,以使您更好地了解到底出了什么问题。但不总是。即使有响应正文,默认情况下也可能不会显示它,具体取决于您的PowerShell版本(6及更高版本应该显示它)。
如果您使用的是PowerShell 5.1或更早版本,则可以通过以下方法获取响应正文(如果存在)。
try {
$token = Invoke-WebRequest -Uri "http://web-scsecur-sso.appliarmony.net/TokenService/connect/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
} catch {
$response = $_.Exception.Response
if ($response.StatusCode -eq [System.Net.HttpStatusCode]::BadRequest) {
$stream = $response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($stream)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Warning $responseBody
}
throw
}
答案 1 :(得分:0)
由于尝试成功,我找到了答案。
第一个响应是Invalid_client
第二个响应Invalid_scope,这很难找到解决方案,我只需要在我的身体上插入一个额外的属性(范围)即可。