1

我在尝试在 PowerShell 7 中使用 Invoke-RestMethod 命令时遇到了问题。我可以让它在 PowerShell 5.1 中正常运行,但 7 给了我一个 401 - Unauthorized 消息。

这是 PowerShell 5.1 的命令:

Invoke-RestMethod "http://internalServer/api/job?name=testJob" -Method GET -UseDefaultCredentials -ContentType "application/JSON"

这是 PowerShell 7 的命令:

Invoke-RestMethod "http://internalServer/api/job?name=testJob" -Method GET -UseDefaultCredentials -ContentType "application/JSON" -AllowUnencryptedAuthentication

api 托管在使用 Windows 身份验证的内部服务器上。当我通过 Fiddler 跟踪请求时,这两个命令似乎都得到了 401 响应,但 PowerShell 5.1 使用该响应生成 Authorization: Negotiate YII{token} 标头,而 PowerShell 7 停止并返回错误。有没有其他人遇到过这个?

4

1 回答 1

1

正如评论中所指出的,这里有一个重定向。默认情况下,身份验证不会在重定向后继续存在,但您可以使用-PreserveAuthorizationOnRedirect参数来控制它Invoke-RestMethod

$irmParams = @{
  Uri = "http://internalServer/api/job?name=testJob"
  Method = 'GET'
  UseDefaultCredentials = $true
  ContentType = 'application/json'
  PreserveAuthorizationOnRedirect = $true # <== Should be your solution
  AllowUnencryptedAuthentication = $true # <=== You should not be using this :)
}

Invoke-RestMethod @irmParams

感谢 OP 的一些额外的工作-PreserveAuthorizationOnRedirect

只会保留对 a 发出的请求的身份验证标头,Uri其中包括原始Uri的直到最后一个/. 文档不包括的是后续Uri的 ' 也必须与原始Uri.

在 OP 的情况下,重定向改变了原始的大小写Uri,因此即使他们指定了-PreserveAuthorizationOnRedirect.

于 2021-09-01T14:59:50.740 回答