REST-API基本身份验证和通过Powershell调用WebRequest

时间:2020-05-28 04:10:07

标签: powershell .net-core base64 powershell-core

尝试通过Powershell客户端连接到REST-API。在Postman中测试端点时,我一点都没有问题。这是函数的主要部分(我有一个[pscredential]$Creds参数,用于获取用户名和密码):

[string]$username = $Creds.UserName
[string]$password = (New-Object System.Net.NetworkCredential($Creds.UserName, $Creds.Password, 'Null')).Password
[string]$authorizationInfo= ([Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f $username, $password))))

Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method Get -Headers @{Authorization = ('Basic {0}' -f $authorizationInfo)}

由于某种原因,我的脚本中的Authorization标头与Postman中的标头不同。我什至可以将Authorization标头复制出Postman并将其粘贴到-Headers参数中,一切正常。我只是看不到我在哪里弄错了。

1 个答案:

答案 0 :(得分:0)

我无法告诉您为什么无法正常工作,但是我可以建议使用API​​一直对我有用的东西:

$auth = $username + ':' + $upassword
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$authorizationInfo = [System.Convert]::ToBase64String($Encoded)
$headers = @{"Authorization"="Basic $($authorizationInfo)"}

Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method GET -Headers $headers

如果这不起作用,请尝试使用Invoke-Restmethod的这种细微差别:

Invoke-RestMethod -Uri "https://$($HostName)/api/" -Method GET -Headers $headers

使用API​​总是冒险。继续尝试。 :)