运行简单的未经授权的Rest查询时发生意外错误

dro*_*oss 33 rest powershell

我有一个不执行身份验证检查的休息端点.我可以从Linux运行一个简单的curl命令:

curl -k https://application/api/about
Run Code Online (Sandbox Code Playgroud)

这回应了.

但是,如果在PowerShell上尝试以下操作,则会失败:

Invoke-RestMethod https://application/api/about
Run Code Online (Sandbox Code Playgroud)

然后我得到:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-RestMethod $Application
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何解决这个问题?

编辑:

尝试使用Invoke-WebRequest:

Invoke-WebRequest -Uri "https://application/api/about"
Run Code Online (Sandbox Code Playgroud)

Invoke-WebRequest:基础连接已关闭:发送时发生意外错误.在行:1 char:1 + Invoke-WebRequest -Uri" https:// application/api/a ... + ~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation :(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-WebRequest],WebException + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

dro*_*oss 72

使用:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Run Code Online (Sandbox Code Playgroud)

取自 Powershell 3.0 Invoke-WebRequest HTTPS在所有请求上失败.


Jus*_*tin 15

就我而言,TLS技巧无效,这似乎是Powershell中的错误。您需要使用.net代码而不是scriptblock添加回调。

#C# class to create callback
$code = @"
public class SSLHandler
{
    public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
    {

        return new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
    }

}
"@

#compile the class
Add-Type -TypeDefinition $code

#disable checks using new class
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()
#do the request
try
{
    invoke-WebRequest -Uri myurl -UseBasicParsing
} catch {
    # do something
} finally {
   #enable checks again
   [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,而设置`[System.Net.ServicePointManager] :: ServerCertificateValidationCallback = {$ true}`和`[System.Net.ServicePointManager] :: CertificatePolicy = New-Object TrustAllCertsPolicy`却没有。 (3认同)