【问题标题】:Invoke-RestMethod returning 401 - Unauthorized in Powershell 7Invoke-RestMethod 返回 401 - Powershell 7 中未经授权
【发布时间】:2021-09-01 13:27:50
【问题描述】:

我在尝试在 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 停止并返回错误。有没有其他人遇到过这种情况?

【问题讨论】:

  • 没有重定向是吗?
  • 另外,如果你设置$env:DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER = 0,它是否可以在PS Core中工作?
  • 当他们提交第一个请求时,他们都会收到 301 响应,之后命令发出的请求是他们收到 401 响应的地方。
  • 啊,那我有你的解决方案了
  • 更改环境变量后仍然出现 401 错误

标签: powershell powershell-core invoke-restmethod


【解决方案1】:

如 cmets 所示,此处正在进行重定向。默认情况下,身份验证不会在重定向后继续存在,但您可以使用 -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

Thanks to some additional legwork by OP-PreserveAuthorizationOnRedirect

将只保留对Uri 发出的请求的身份验证标头,其中包括原始Uri 直到最后一个/。文档没有包含的是后续的Uri 也必须与原始Uri 的大小写匹配。

在 OP 的情况下,重定向改变了原始 Uri 的大小写,因此即使他们指定了 -PreserveAuthorizationOnRedirect,也会破坏重定向身份验证。

【讨论】:

  • 即使我包含 MaximumRedirection 参数并将其提高到 10,它仍然给我 401 错误
  • 抱歉,我删除了 -MaximumRedirection 部分,错误的情报。但是-PreserveAuthorizationOnRedirect 是您所需要的。
  • 它似乎也不适用于该参数。
  • 在深入研究 .NET Core 的 HttpWebRequest 之后,我发现 PreAuthenticate 属性(我认为 PreserveAuthorizationOnRedirect 正在使用)只会保留对 uri 发出的请求的身份验证标头,其中包括原始 uri 直到最后一个“/”。 docs.microsoft.com/en-us/dotnet/api/… 文档没有包含的是后续 uri 也必须与原始 uri 的大小写匹配。重定向将 uri 的一部分切换为小写,其中原始具有大写
  • 最后一条评论空间不足。将原始 uri 更改为小写后,PreserveAuthorizationOnRedirect 现在可以工作了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-06-20
  • 2023-03-09
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2014-07-03
相关资源
最近更新 更多