rest - powershell http发布REST API基本身份验证

标签 rest powershell

我具有使用curl使用REST API的基本身份验证:

curl -X POST  -H 'Accept: application/json' -u user:password http://localhost/test/

但是,当我尝试对powershell webRequest执行相同操作时,得到403(权限被拒绝)。
当我在REST代码中禁用身份验证检查时,此脚本可以正常工作。

在Powershell中与curl类似的在POST请求上传递凭据的最佳方法是什么,或者我该如何解决以下脚本。

非常感谢您对此提供一些指导。谢谢。

这是我的powershell脚本:
function Execute-HTTPPostCommand() {
    param(
        [string] $target = $null
    )

    $username = "user"
    $password = "pass"

    $webRequest = [System.Net.WebRequest]::Create($target)
    $webRequest.ContentType = "text/html"
    $PostStr = [System.Text.Encoding]::UTF8.GetBytes($Post)
    $webrequest.ContentLength = $PostStr.Length
    $webRequest.ServicePoint.Expect100Continue = $false
    $webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password 

    $webRequest.PreAuthenticate = $true
    $webRequest.Method = "POST"

    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($PostStr, 0,$PostStr.length)
    v$requestStream.Close()

    [System.Net.WebResponse] $resp = $webRequest.GetResponse();
    $rs = $resp.GetResponseStream();
    [System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
    [string] $results = $sr.ReadToEnd();

    return $results;

}


$post = "volume=6001F930010310000195000200000000&arrayendpoint=2000001F930010A4&hostendpoint=100000051ED4469C&lun=2"

$URL = "http://example.com/test/"

Execute-HTTPPostCommand $URL

最佳答案

您的代码看起来不错,我会尝试为$ webrequest添加HTTP_AUTHORIZATION header ,如下所示:

$webRequest.Headers.Add("AUTHORIZATION", "Basic YTph");

其中YTph是用户名:密码的base64编码的字符串。

关于rest - powershell http发布REST API基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8919414/

相关文章:

powershell - 哪些 cmdlet 使用 IHostUISupportsMultipleChoiceSelection 接口(interface)来提示选择?

powershell - 使用 PowerShell 隐藏 Windows 终端控制台窗口

powershell - 你能用Powershell编写Windows服务吗

c# - 质疑使用具有 Restful 服务的 DTO 并从更新中提取行为

java - 等待 API 响应的 RESTTemplate

php - 开发 Web 服务时可能遇到的一些陷阱/技巧是什么

excel - 使用带有 MICROSOFT.ACE.OLEDB.12.0 的 Powershell 在 CSV XML XLS XLSX XLSM 之间进行转换

java - Json反序列化并在启动时保存到JPA

rest - 在 Grails 中发送带有 JSON 负载的 HTTP POST 的最佳方式

Powershell:将文件夹和子文件夹中的所有文件移至单个文件夹中