1

在遇到尝试进行 REST API 调用并避免自签名证书问题后,我试图更好地理解 PowerShell 中的 Add-Type。代码如下。

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;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("InternalApiKey", "d472f0e9-23c9-4fff-aec9-cc1f2d5d6a85")

$response = Invoke-RestMethod 'https://localhost:9443/api/GetStats/' -Method 'GET' -Headers $headers
$response | ConvertTo-Json

当我运行它时,它会因错误而中断。

“新对象:找不到类型 [TrustAllCertsPolicy]:验证是否已加载包含此类型的程序集。” 然后,因为失败了,我得到了错误,“Invoke-RestMethod:远程证书无效,因为证书链中的错误:PartialChain”

只是偶然发现它在 PowerShell 5.1.22000.282 中按预期工作而在 PowerShell 7.2.1 中没有。我可以进行哪些更改以使其在两个版本的 PowerShell 中都能正常工作?

更新:这个链接有一些代码可以让它在两个版本的 PowerShell 中运行。我接受了我所做的答案,因为它是最有帮助的,并且因为我正在分享另一个答案。 https://github.com/PowerShell/PowerShell/issues/7092

4

2 回答 2

3

在 PowerShell 7.x 中,Web cmdlet 有一个-SkipCertificateCheck您可以使用的开关:

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("InternalApiKey", "d472f0e9-23c9-4fff-aec9-cc1f2d5d6a85")

$response = Invoke-RestMethod 'https://localhost:9443/api/GetStats/' -SkipCertificateCheck -Method 'GET' -Headers $headers

如果端点已经在发送 JSON,您不妨Invoke-WebRequest改用(而不是让Invoke-RestMethod从 JSON 转换为对象,然后再返回ConvertTo-Json):

$response = Invoke-WebRequest 'https://localhost:9443/api/GetStats/' -SkipCertificateCheck -Method 'GET' -Headers $headers
$response.Content # this now contains the body of the raw response from the API, eg. JSON/XML/whatever
于 2022-01-26T12:41:17.067 回答
1

添加类型 @" 使用 System.Net;使用 System.Security.Cryptography.X509Certificates;

public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}

"@ [System.Net.ServicePointManager]::CertificatePolicy = 新对象 TrustAllCertsPolicy

$headers = 新对象 "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("InternalApiKey", "d472f0e9-23c9-4fff-aec9-cc1f2d5d6a85")

$response = Invoke-RestMethod 'https://localhost:9443/api/GetStats/' -Method 'GET' -Headers $headers $response | 转换为 JSON

于 2022-01-26T13:27:12.730 回答