【问题标题】:powershell http post REST API basic authenticationpowershell http post REST API 基本身份验证
【发布时间】:2012-02-13 17:16:59
【问题描述】:

我使用 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

【问题讨论】:

    标签: rest powershell


    【解决方案1】:

    Credentials 属性似乎用于 Windows 身份验证。尝试使用此功能: Forcing Basic Authentication in WebRequest 在任何情况下,我都会建议您使用一些网络调试器,例如 Fiddler 来查看 curl 请求和您的请求之间的区别

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 谢谢!这是为我做的。
      【解决方案3】:

      我知道这是一个旧线程,但对于那些可能偶然发现这个问题的人来说,invoke-rest 方法是一种更好、更简单的工具,用于使用 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 Business Manager 和 Jira 一起工作。

      【讨论】:

      • 所有注意事项:Invoke-RestMethod 对我来说适用于大多数 JIRA rest api 远程调用。但是,我发现更新问题的修复版本和影响版本需要Invoke-WebRequestfixVersionsversions,经过广泛测试)。如果您遇到超时,请考虑至少切换这两个。这是我们的私有服务器 JIRA 的问题,但不是我的个人云 JIRA 实例。
      【解决方案4】:

      这是我用来从 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 Prompted 可用于要求用户输入他们的登录信息。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        • 2016-06-08
        • 1970-01-01
        相关资源
        最近更新 更多