PHP中具有基本身份验证的SOAP XML请求

时间:2018-12-12 08:24:14

标签: php xml api web-services soap

我正在尝试使用HTTP基本身份验证在PHP中设置SOAP请求。由于某些原因,我不断收到 HTTP / 1.1 401 Unauthorized 错误。

这是我要创建的请求的示例:

POST https://url/someurl/soap HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "SomeSoapAction"
User-Agent: SomeUser Client-HttpClient/3.1
Content-Length: 1503
Authorization: Basic dGsomebasicreyteryheyp0ZXN0ZXI=
Host: somehost.com  

这是我的代码的片段:

ini_set('display_errors',1);
ini_set("soap.wsdl_cache_enabled", "0");
error_reporting(E_ALL);
$wsdl = "urltosomewsdlfile.wsdl";
$url = "somerl";
$username = "username";
$password = "password";
$encodedstuff = base64_encode("{$username}:{$password}");

$client = new SoapClient($wsdl, array('exceptions' => true,'trace' => true,'login' => 'somelogin', 'password' => 'somepw'));
$header = new SoapHeader($url, 'Authorization: Basic', $encodedstuff);
$client->__setSoapHeaders($header);

try {
    $result = $client->SomeSoapAction();
    } catch (SoapFault $soapFault) {
        var_dump($soapFault);
        echo "<br />Request :<br />", htmlentities($client->__getLastRequest()), "<br />";
        echo "<br />Response :<br />", htmlentities($client->__getLastResponse()), "<br />";
    }

如果我从 new SoapClient部分中取出用户名和密码,则会引发未捕获的SoapFault异常:[WSDL] SOAP-ERROR:解析WSDL:无法从中加载。

如果我将base64编码变量放入 new SoapClient部分,而不是用户名/ pw,则会引发与上述相同的解析错误:      $ client = new SoapClient($ wsdl,array('authentication'=>“ Basic $ encodedstuff”,'exceptions'=> true,'trace'=> true,));

直接加载URL时,用户名和密码有效。

有人能指出我正确的方向吗?感谢您的帮助。


更新12/18/18:我一直在尝试将其作为建议的新方法,但仍收到相同的401错误消息:

$opts = array( 'http'=>array( 'method'=>"POST", 'header' => "Authorization: Basic " . base64_encode("{$user}:{$pw}") ) ); 
$context = stream_context_create($opts); 
$client = new SoapClient($wsdl, array('stream_context' => $context,'exceptions' => true,'trace' => true,)); 
$header = new SoapHeader($url, 'Authorization: Basic', $encodedstuff); 
$client->__setSoapHeaders($header);

更新15/01/19: 我仍然对此有疑问。

使用SOAPUI,我可以发出成功的请求并获得身份验证。我看不出SOAPUI请求和我自己的PHP请求之间有什么区别。

我注意到我的PHP代码创建的请求标头更改了POST和Host端点URL。 POST URL的第一部分删除了域,主机也删除了URL的第一部分。

SOAPUI请求标头(正确返回200):

POST https://test-example.com/file/SOAP HTTP/1.1
Host: test-example.com

PHP请求标头(返回401):

POST /file/SOAP HTTP/1.1
Host: example.com

这似乎是导致问题的原因,好像我指向错误的端点一样。对于打破我的请求的PHP代码可能有什么问题,有人有建议吗?谢谢。

0 个答案:

没有答案