15

PHP SoapClient 标头。我在获取子节点中的命名空间时遇到问题。这是我正在使用的代码:

$security = new stdClass;
$security->UsernameToken->Password = 'MyPassword';
$security->UsernameToken->Username = 'MyUsername';
$header[] = new SOAPHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', $security);
$client->__setSoapHeaders($header);

这是它生成的 XML:

<ns2:Security>
  <UsernameToken>
    <Password>MyPassword</Password>
    <Username>MyUsername</Username>
  </UsernameToken>
</ns2:Security>

这是我希望它生成的 XML:

<ns2:Security>
  <ns2:UsernameToken>
    <ns2:Password>MyPassword</ns2:Password>
    <ns2:Username>MyUsername</ns2:Username>
  </ns2:UsernameToken>
</ns2:Security>

我需要将命名空间引用放入 UsernameToken、Password 和 Username 节点。任何帮助将非常感激。

谢谢。

4

2 回答 2

14

David has the right answer. And he is also right that it takes way too much effort and thought. Here's a variation that encapsulates the ugliness for anyone working this particular wsse security header.

Clean client code

$client = new SoapClient('http://some-domain.com/service.wsdl');
$client->__setSoapHeaders(new WSSESecurityHeader('myUsername', 'myPassword'));

And the implementation...

class WSSESecurityHeader extends SoapHeader {

    public function __construct($username, $password)
    {
        $wsseNamespace = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
        $security = new SoapVar(
            array(new SoapVar(
                array(
                    new SoapVar($username, XSD_STRING, null, null, 'Username', $wsseNamespace),
                    new SoapVar($password, XSD_STRING, null, null, 'Password', $wsseNamespace)
                ), 
                SOAP_ENC_OBJECT, 
                null, 
                null, 
                'UsernameToken', 
                $wsseNamespace
            )), 
            SOAP_ENC_OBJECT
        );
        parent::SoapHeader($wsseNamespace, 'Security', $security, false);
    }

}
于 2013-12-10T15:35:08.340 回答
12

弄清楚了。我使用了嵌套的 SoapVars 和数组。

$ns_s = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
$node1 = new SoapVar('MyUsername', XSD_STRING, null, null, 'Username', $ns_s);
$node2 = new SoapVar('MyPassword', XSD_STRING, null, null, 'Password', $ns_s);
$token = new SoapVar(array($node1,$node2), SOAP_ENC_OBJECT, null, null, 'UsernameToken', $ns_s);
$security = new SoapVar(array($token), SOAP_ENC_OBJECT, null, null, 'Security', $ns_s);
$header[] = new SOAPHeader($ns_s, 'Security', $security, false);

这完全花费了太多的努力和思考......

于 2012-11-20T16:17:03.570 回答