使用 Windows 商店证书的 Powershell Invoke-RestMethod 调用(基本授权?)

问题描述 投票:0回答: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
命令的三行分别失败了:

  • 错误的标题(这是预期的,但我尝试了)
  • 授权为空或方案不基础
  • 未找到证书指纹

我已经完成了其余呼叫,因此我可以告诉服务正在应答,但我不想在我的脚本中使用 user:pass 。


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

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

rest powershell x509certificate certificate-store
1个回答
0
投票
@{"AUTHORIZATION"="Basic Base64Encode(user:pass)"}

修复了“底层连接已关闭”问题。

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

© www.soinside.com 2019 - 2024. All rights reserved.