PowerShell 使用自签名证书连接到 REST API。

标签 powershell ssl

我正在尝试调用设备上的 REST API,但它使用 https 套接字的自签名证书。我尝试在 PowerShell 中更改以下内容

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

但是在使用以下方式调用电话时,

$uri = 'https://hostname/api/config'
$headers = @{"Authorization"="token apitokengoeshere"}
try {
Invoke-RestMethod -Uri $uri -Headers $headers
}
catch {
$_.Exception |format-list -force
}

但我仍然收到以下错误

Status         : SendFailure
Response       :
Message        : The underlying connection was closed: An unexpected 
error occurred on a send.
Data           : {}
InnerException : System.IO.IOException: Unable to read data from the 
                transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection       was forcibly closed by the remote host
               at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
               at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
                --- End of inner exception stack trace ---
                at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
                at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
TargetSite     : System.Net.WebResponse 
GetResponse(System.Net.WebRequest)
StackTrace     :    at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
                    at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
HelpLink       :
Source         : Microsoft.PowerShell.Commands.Utility
HResult        : -2146233079

我什至尝试安装 Tunable-SSL Powershell 模块,如博客中提到的 Here关于之前的问题。

最佳答案

我编写了一个简单的脚本,用于检查具有自签名证书的 HTTPS 页面上的结果代码状态。

通过大量谷歌搜索,这就是我最终得到的结果:

Add-Type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@ -ea SilentlyContinue -wa SilentlyContinue    

然后在 Invoke-WebRequest 调用之前执行以下操作: [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

关于PowerShell 使用自签名证书连接到 REST API。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289236/

相关文章:

powershell - powershell版本号比较

windows - 在 Windows Server 数据中心找不到 WebAdministration powershell 模块

powershell - 根据Get-AdUser的结果设置AD用户的UPN

iis - "PS c:\> New-WebSite -Blah:"抛出索引超出数组范围

azure - 从 Azure 中的虚拟网络网关获取虚拟网络详细信息

java - 使用来自 java 的证书连接到 web 服务

php - 如何在 PHP 中使用 Doctrine2 设置 SSL 加密的 MySQL 连接(不是 Symfony,不是 Doctrine1)

ssl - 如何将 https 用于许多带有 http 记录的自定义域

web-services - 使用 CodeIgniter API 进行身份验证

android - SSL证书安卓