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

时间:2012-01-19 00:12:23

标签: rest powershell

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

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

但是,当我尝试使用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

4 个答案:

答案 0 :(得分:18)

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

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

其中YTph将是username:password。

的base64encoded字符串

答案 1 :(得分: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

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

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

答案 2 :(得分:4)

Credentials属性似乎用于Windows身份验证。尝试使用此功能: Forcing Basic Authentication in WebRequest 无论如何,我建议你使用一些网络调试器,比如Fiddler来查看curl请求和你的请求之间的区别

答案 3 :(得分:0)

这是我用来从Confluence下载页面作为HTML文件的代码。

$pageid = "176398584" ;
$url = "http://wikiserver/wiki/pages/viewpage.action?pageId=$pageid" ;
write-host "Establish credentials" ;
$r = Invoke-WebRequest "http://wikiserver/wiki/pages/login.action" -SessionVariable my_session ;
# $r ;
$form = $r.Forms[1]; 
# $form ; 

# $c = $host.UI.PromptForCredential('Your Credentials', 'Enter Credentials', '', '') ;
# $form.fields['os_username'] = $c.UserName ;
# $form.fields['os_password'] = $c.GetNetworkCredential().Password ;
$form.fields['os_username'] = "mywikirobotlogonname" ;
$form.fields['os_password'] = "mywikirobotpassword"  ;
$form.fields['os_cookie']      = "true" ; 
$form.fields['os_destination'] = "%2Fpages%2Fviewpage.action%3FpageId%3D$pageid" ; 

$outputFile = "$pageid.html" ;
$content = Invoke-WebRequest -Uri ($url + $form.Action)  -WebSession $my_session -Method POST -Body $form.Fields ;
$content.ParsedHTML.getElementById("content").innerHTML | Add-Content $outputFile

主机UI提示可用于要求用户输入其登录信息。

取消注释变量以向系统输出显示表单内容,检索到的页面等以进行故障排除 - $ r $ form $ content