简体   繁体   English

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

[英]powershell http post REST API basic authentication

I have basic authentatication working with REST API using curl: 我使用curl使用REST API进行基本认证:

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

But, when I try to do the same with powershell webRequest, I get 403(permission denied). 但是,当我尝试使用powershell webRequest时,我得到403(许可被拒绝)。 This script works fine when I disable authentication check in REST code. 当我在REST代码中禁用身份验证检查时,此脚本正常工作。

What is the best way in powershell to pass credentials on POST request similar to curl or what can I do to fix following script. PowerShell在POST请求上传递凭据的最佳方式是什么,类似于curl,或者我可以做些什么来修复以下脚本。

Would really appreciate some guidance on this. 非常感谢对此的一些指导。 Thanks. 谢谢。

Here is my powershell script: 这是我的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

Your code looks good, I would try adding HTTP_AUTHORIZATION header for $webrequest like this: 你的代码看起来不错,我会尝试为$ webrequest添加HTTP_AUTHORIZATION标头,如下所示:

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

Where YTph would be the base64encoded string for username : password. 其中YTph将是username:password的base64encoded字符串。

I know this is an old thread, but for those who might stumble across this the invoke-restmethod is a much better, and simpler, vehicle for making API calls with PowerShell. 我知道这是一个旧线程,但对于那些可能偶然发现这种情况的人来说,invoke-restmethod是一个更好,更简单的工具,用于使用PowerShell进行API调用。

Build a parameter list as a hash table: 将参数列表构建为哈希表:

$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

Your parameter hash table may differ slightly. 您的参数哈希表可能略有不同。

I actually haven't gotten this to work with Trello, but I have with GitHub, Serena Business Manager and Jira. 我实际上还没有和Trello一起工作,但我和GitHub,Serena业务经理和Jira一起工作。

Credentials property seems to be used for Windows authentication. 凭据属性似乎用于Windows身份验证。 Try using this function: Forcing Basic Authentication in WebRequest I would advise you in any case to use some web debugger, like Fiddler to see the difference between curl request and your request 尝试使用此功能: 在WebRequest中强制执行基本身份验证我建议您在任何情况下使用一些Web调试器,如Fiddler来查看curl请求和您的请求之间的区别

This is the code I use to download pages from Confluence as HTML files. 这是我用来从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

The host UI Prompted can be used to ask the user to enter their logon information. 主机UI提示可用于要求用户输入其登录信息。

Uncomment a variable to display to the system output the contents of the form, the retrieved page, etc to troubleshoot- $r $form $content 取消注释变量以向系统输出显示表单内容,检索到的页面等以进行故障排除 - $ r $ form $ content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM