【问题标题】:Can't translate curl to Invoke-WebRequest in PowerShell (--insecure/-k not found)无法在 PowerShell 中将 curl 转换为 Invoke-WebRequest(--insecure/-k not found)
【发布时间】:2018-08-30 18:23:34
【问题描述】:

我有原始的 curl 调用,据说它在 Unix 环境中工作(或他们在提供商办公室使用的任何东西)。

curl 
  -u ybeepbeepbeepa:eboopboopboopa
  -k 
  -d "grant_type=mobile&customerId=SE.B2C/abcd&pin=1234&scope=openid" 
  -H "Content-Type:application/x-www-form-urlencoded" 
  https://xxx/oauth2/token

使用docs for curl,我将标志和属性交换为以下内容。

Invoke-WebRequest 
  -User ybeepbeepbeepa:eboopboopboopa 
  -Method POST 
  -Headers @{"Content-Type"="application/x-www-form-urlencoded"} 
  -Uri "https://xxx/oauth2/token?grant_type=mobile&customerId=SE.B2C/abcd&pin=1234&scope=openid" 

我唯一没有翻译的部分是-k,它应该相当于--insecure。检查了上述文档,我找到了一些可能的替代方案,虽然有些牵强(例如 -AllowUnencryptedAuthentication),但它们都失败了,我没有想法。

  1. PowerShell 的 Invoke-WebRequest 中 curl 的 --insecure(或 -k)的等价物(它意外地被赋值为 curl,因为标志不同,所以像鸭子一样令人困惑)?
  2. 命令的其余部分是否正确移植到 PowerShell? (我已经将一些标志与 URL 一起作为 querty 字符串打包。而且我并不完全确定 Headers 的语法。)

【问题讨论】:

标签: powershell curl


【解决方案1】:

代替-k,您需要使用ServicePointManager 类为应用程序域设置证书验证例程:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }

对于-u 标志,您需要自己construct the Basic Authentication header

function Get-BasicAuthCreds {
    param([string]$Username,[string]$Password)
    $AuthString = "{0}:{1}" -f $Username,$Password
    $AuthBytes  = [System.Text.Encoding]::Ascii.GetBytes($AuthString)
    return [Convert]::ToBase64String($AuthBytes)
}

$Headers = @{"Content-Type"="application/x-www-form-urlencoded"} 
$Headers['Authorization'] = "Basic $(Get-BasicAuthCreds ybeepbeepbeepa eboopboopboopa)"

Invoke-WebRequest -Method POST -Headers $Headers -Uri "https://xxx/oauth2/token?grant_type=mobile&customerId=SE.B2C/abcd&pin=1234&scope=openid"

如果你想内联生成凭证字符串,你可以这样做(虽然它有点笨拙):

$Headers = @{
  "Content-Type"  = "application/x-www-form-urlencoded"} 
  "Authorization" = "Basic $([Convert]::ToBase64String([System.Text.Encoding]::Ascii.GetBytes('ybeepbeepbeepa:eboopboopboopa')))"
}

【讨论】:

  • 是否可以内联而不是函数来表达?
  • 太棒了。不过,这仍然是两行执行。我希望有一个内联的 单行,我可以将它作为一种神奇的药丸发送给我的同事(你知道 - 粘贴并按 Enter,不假思索)。不过,我认为,只要我们可以在 PowerShell 中执行变量声明,这就足够了。 (在访问 $PROFILE 文件时,我们受到了极大的限制。)
  • -replace '\r?\n',';' ;-)
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 2020-02-28
  • 2017-12-12
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2013-02-20
  • 2020-10-14
相关资源
最近更新 更多