Powershell Invoke-RestMethod Call using Windows store certif



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

我想在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:LocalMachineMy | Where-Object {$_.Subject -match $Remote_CertificateName}).Thumbprint;
$Certificate = Get-ChildItem -Path Cert:LocalMachineMy$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中,如何使用本地Windows存储中运行Invoke-RestMethod命令的证书?

谢谢你的帮助

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

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

最新更新