Powershell 从 api 调用中请求 Bearer 令牌

Powershell request Bearer token from api call

我在 Powershell 中有一个脚本,我在其中请求 Bearer 令牌稍后做一些事情。 问题是,我总是收到 Bad-Request (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 令牌,但到目前为止我什么也没收到。

来自 Web 服务器的 HTTP 400(错误请求)响应告诉您它不喜欢您的请求,并且拒绝执行任何操作。问题可能有很多(正文参数中的错字、错误的 url、invalid/expired 秘密等)。

某些 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
}

感谢 try-catch 我找到了答案。

第一条回复是Invalid_client

第二个回复 Invalid_scope,这有点难找到解决方案,我只需要插入一个额外的 属性,范围,到我的 body.