1

我想从托管远程证书的 Windows 服务器调用远程 Rest Web 服务。我已从远程服务器导出证书并将其添加到 Windwos 商店。(/个人/myCert)

我想在 Invoke-RestMethod PowerShell 命令上使用它。下面是我尝试过的代码

# Variables
$Remote_Uri = "https://remote.example.com/service/search"
$Remote_CertificateName = "myCert"
$Remote_ApiKey = "oisdjfSOEDJFKQDfSDKFjsQDKFJ"
$Remote_ContentType = "application/json"
$LocalArtifactPath = "C:\RemoteObjects.json"

# Get Certificate
$Remote_CertificateThumbprint = (Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match $Remote_CertificateName}).Thumbprint;
$Certificate = Get-ChildItem -Path Cert:\LocalMachine\My\$Remote_CertificateThumbprint

# Basic Encoding
$encoding = [System.Text.Encoding]::ASCII.GetBytes($Certificate)
$encodedString = [System.Convert]::ToBase64String($encoding)
$BasicAuth = "Basic " + $encodedString

# Set Headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization", $BasicAuth)
$Headers.Add("api", $Remote_ApiKey)
$Headers.Add("Content-Type", $Remote_ContentType)

# Self-signed certificate
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } 

# Call Rest Service
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -Headers $Headers 
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -Certificate $Certificate
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -CertificateThumbprint $Remote_CertificateThumbprint

# Self-signed certificate off
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null

带有命令的三行Invoke-RestMethod分别失败:

  • 错误的标题(这是意料之中的,但我试了一下)
  • 授权为空或方案不是基本的
  • 找不到证书指纹

我已经接听了其余的电话,@{"AUTHORIZATION"="Basic Base64Encode(user:pass)"}所以我可以告诉服务正在应答,但我不想在我的脚本中使用 user:pass。

我想使用已添加到 Windows 应用商店的证书。我想知道两件事:

  • “基本”授权方案是否适合与证书一起使用?
  • 在 powershell 中,如何使用运行 Invoke-RestMethod 命令的本地 Windows 商店的证书?

谢谢您的帮助

4

1 回答 1

0

在我的脚本中添加这个[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12修复了“底层连接已关闭”问题。

在此之前交叉检查您的系统中是否启用了 IIS。

于 2018-10-31T10:16:52.493 回答