Collecting/Processing headers in PHP Soap Server

2020-07-07 10:47发布

I'm creating a web service using PHP5's native SOAP Methods. Everything went fine until I tried to handle authentication using SOAP Headers.

I could easily find how to add the username/password to the SOAP headers, client-side:

$myclient = new SoapClient($wsdl, $options);

$login = new SOAPHeader($wsdl, 'email', 'mylogin');
$password = new SOAPHeader($wsdl, 'password', 'mypassword');
$headers = array($login, $password);

$myclient->__setSOAPHeaders($headers);

But I can't find anywhere the methods for collecting and processing these headers server-side. I'm guessing there has to be an easy way to define a method in my SoapServer that handles the headers...

4条回答
做个烂人
2楼-- · 2020-07-07 11:21

SoapClient uses the username and password to implement HTTP authentication. Basic and Digest authentication are support (see source)

For information on implementing HTTP authentication in PHP on the server side, see this manual page.

If you don't want to use HTTP authentication, see this user-contributed sample on the SoapServer manual page which shows how you could pass some credentials in a UsernameToken header.

查看更多
一夜七次
3楼-- · 2020-07-07 11:27

You can try reading RAW POST data.

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
    $xml = file_get_contents('php://input');
    print( htmlspecialchars( $xml ) );
    // XML processing
}

In $xml you will have the whole SOAP XML request.

SoapServer does not have methods for reading SOAP headers.

-- edit: contributed example from manual does not seem to work, header handling method never gets called

查看更多
冷血范
4楼-- · 2020-07-07 11:29

You have to use a current version of PHP. With PHP 5.2.4 I had the same problem, but with 5.2.17 or 5.3.8 the callback for SOAP header handling (described in the user-contributed samle on php.net) gets called and everything works pretty fine.

查看更多
干净又极端
5楼-- · 2020-07-07 11:37

With a modern PHP version it is NOT necessary to add anything to the WSDL as the headers are part of the SOAP Envelope specification.

The user contributed example cited by Paul Dixon does not work simply because the header is not UserToken as written in the comment, the header is Security, so that's is the name the class method should have. Then you get a nice stdClass object with a UserToken stdClass object property that has Username and Password as properties.

Example code (to be inserted in a PHP class that implements the SOAP service:

   public function Security( $header  ){
      $this->Authenticated = true; // This should be the result of an authenticating method
      $this->Username = $header->UsernameToken->Username;
      $this->Password = $header->UsernameToken->Password;
    }

Works like a charm for Username/Password based WSSE Soap Security

查看更多
登录 后发表回答