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

R D*_*R D 20 rest powershell

我使用curl使用REST API进行基本认证:

curl -X POST  -H 'Accept: application/json' -u user:password http://localhost/test/
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用powershell webRequest时,我得到403(许可被拒绝).当我在REST代码中禁用身份验证检查时,此脚本正常工作.

powershell在POST请求上传递凭据的最佳方式是什么,类似于curl,或者我可以做些什么来修复以下脚本.

非常感谢对此的一些指导.谢谢.

这是我的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
Run Code Online (Sandbox Code Playgroud)

Raj*_*j J 18

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

$webRequest.Headers.Add("AUTHORIZATION", "Basic YTph");
Run Code Online (Sandbox Code Playgroud)

其中YTph将是username:password的base64encoded字符串.


小智 17

我知道这是一个旧线程,但对于那些可能偶然发现这种情况的人来说,invoke-restmethod是一个更好,更简单的工具,用于使用PowerShell进行API调用.

将参数列表构建为哈希表:

$params = @{uri = 'https:/api.trello.com/1/TheRestOfYourURIpath';
                   Method = 'Get'; #(or POST, or whatever)
                   Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($acctname):$($password)"));
           } #end headers hash table
   } #end $params hash table

$var = invoke-restmethod @params
Run Code Online (Sandbox Code Playgroud)

您的参数哈希表可能略有不同.

我实际上还没有和Trello一起工作,但我和GitHub,Serena业务经理和Jira一起工作.