使用PowerShell使用未签名的证书查询REST API

时间:2018-07-05 04:57:24

标签: powershell ssl visual-studio-code

我最近从使用PowerShell ISE切换为使用Visual Studio代码

当我在办公室PC(Win 10 64位)上的VSC中运行PowerShell脚本时,使用HTTPS上使用Invoke-RestMethod的REST连接将不会对使用未签名SSL证书的服务器进行身份验证。在家用PC上的VSC上(也是Win 10 64bit)运行时,一切正常。

PowerShell中有一个使用System.Net.Security来处理未签名的SSL证书的功能,当我以本机PowerShell或从ISE运行代码时,该功能可以完美运行

这是我通过自签名证书通过SSL会话补偿Invoke-RestMethod的方式:

if (-not("dummy" -as [type])) {
  add-type -TypeDefinition @"
  using System;
  using System.Net;
  using System.Net.Security;
  using System.Security.Cryptography.X509Certificates;

  public static class Dummy {
    public static bool ReturnTrue(object sender,
    X509Certificate certificate,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors) {
        return true;
    }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Dummy.ReturnTrue);
    }
  }
"@
}

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [dummy]::GetDelegate()
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

我还将用户名+密码编码为Base64编码的哈希,该哈希是Invoke-RestMethod调用的标题:

$pair = "${username}:${password}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }

因此完整的呼叫顺序为:

Invoke-RestMethod -Uri "https://theserver.com/rest/api/whatever" -Method Get -Headers $headers

当从ISE内部运行PowerShell或直接执行PowerShell时,托管REST API的服务器(使用Apache Tomcat的Confluence)会接受身份验证,但是如果我尝试从中运行该连接,则会抛出未对连接进行身份验证的响应在VSC中,但只能在办公室的PC上,而不是在家中。我怀疑是安全证书问题或政策互动。

1 个答案:

答案 0 :(得分:0)

我只是将办公室中已有版本的分支与先前版本的分支进行了比较,发现了一个很小的错字,使我不注意密码的情况就搞砸了。

毕竟不是VSC;只是我不勤奋。