powershell http post REST API 基本身份验证 [英] powershell http post REST API basic authentication

查看:46
本文介绍了powershell http post REST API 基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 curl 使用 REST API 进行基本身份验证:

I have basic authentatication working with REST API using curl:

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

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

But, when I try to do the same with powershell webRequest, I get 403(permission denied). This script works fine when I disable authentication check in REST code.

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

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.

真的很感激这方面的一些指导.谢谢.

Would really appreciate some guidance on this. Thanks.

这是我的 powershell 脚本:

Here is my powershell script:

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 标头,如下所示:

Your code looks good, I would try adding HTTP_AUTHORIZATION header for $webrequest like this:

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

其中 YTph 是 username : password 的 base64 编码字符串.

Where YTph would be the base64encoded string for username : password.

这篇关于powershell http post REST API 基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆