How to Implement Ws-Security 1.1 in PHP5

how to implement ws-security 1.1 in php5

On PHP Classes, Roger Veciana i Rovira submitted this (I just reformatted the code):

class WSSoapClient extends SoapClient {

private $username;
private $password;
/*Generates de WSSecurity header*/
private function wssecurity_header() {

/* The timestamp. The computer must be on time or the server you are
* connecting may reject the password digest for security.
*/
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
/* A random word. The use of rand() may repeat the word if the server is
* very loaded.
*/
$nonce = mt_rand();
/* This is the right way to create the password digest. Using the
* password directly may work also, but it's not secure to transmit it
* without encryption. And anyway, at least with axis+wss4j, the nonce
* and timestamp are mandatory anyway.
*/
$passdigest = base64_encode(
pack('H*',
sha1(
pack('H*', $nonce) . pack('a*',$timestamp).
pack('a*',$this->password))));

$auth = '
<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.'.
'org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>'.$this->username.'</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-'.
'wss-username-token-profile-1.0#PasswordDigest">'.$passdigest.'</wsse:Password>
<wsse:Nonce>'.base64_encode(pack('H*', $nonce)).'</wsse:Nonce>
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-'.
'200401-wss-wssecurity-utility-1.0.xsd">'.$timestamp.'</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
';

/* XSD_ANYXML (or 147) is the code to add xml directly into a SoapVar.
* Using other codes such as SOAP_ENC, it's really difficult to set the
* correct namespace for the variables, so the axis server rejects the
* xml.
*/
$authvalues = new SoapVar($auth,XSD_ANYXML);
$header = new SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-".
"200401-wss-wssecurity-secext-1.0.xsd", "Security", $authvalues,
true);

return $header;
}

/* It's necessary to call it if you want to set a different user and
* password
*/
public function __setUsernameToken($username, $password) {
$this->username = $username;
$this->password = $password;
}

/* Overwrites the original method adding the security header. As you can
* see, if you want to add more headers, the method needs to be modifyed
*/
public function __soapCall($function_name, $arguments, $options=null,
$input_headers=null, $output_headers=null) {

$result = parent::__soapCall($function_name, $arguments, $options,
$this->wssecurity_header());

return $result;
}
}

How would a php or java client authenticate if I'm using WCF w/ forms auth?

I managed to authenticate a PHP client, but not without some effort.
At first, I tried the following:

$header = new stdClass;
$credentials = new stdClass;
$credentials->Username="myuser";
$credentials->Password="mypass";
$header->UsernameToken = $credentials;

$securityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
$client->__setSoapHeaders($securityNamespace, 'Security', $header);

It didn't work. It seems that PHP5 (v5.3.5 in my case) has a bug preventing the namespace prefix from appearing inside nested header tags.
http://bugs.php.net/bug.php?id=48966

I ended up with:

<UsernameToken><Username>myuser</Username><Password>myuser</Password></UsernameToken>

instead of:

<o:UsernameToken><o:Username>myuser</o:Username><o:Password>myuser</o:Password></o:UsernameToken>

So, what I had to do was hardcoding the necessary XML in a variable. This is ugly but working:

$securityNamespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
$headerContent = "<o:Security xmlns:o=\"$securityNamespace\">
<o:UsernameToken>
<o:Username>myuser</o:Username>
<o:Password>mypass</o:Password>
</o:UsernameToken>
</o:Security>";
$headerVar = new SoapVar($headerContent, XSD_ANYXML, null, null, null);
$header = new SoapHeader($securityNamespace, 'o:Security', $headerVar);
$client->__setSoapHeaders(array($header));

I hope it will be helpful to someone.
Bye!

Connecting to WS-Security protected Web Service with PHP

The problem seems to be that the WSDL document is somehow protected (basic authentication - I don't thinkg that digest authentication is supported with SoapClient, so you'd be out of luck in this case) and that the SoapClient therefore cannot read and parse the service description.

First of all you should try to open the WSDL location in your browser to check if you're presented an authentication dialog. If there is an authentication dialog you must make sure that the SoapClient uses the required login credentials on retrieving the WSDL document. The problem is that SoapClient will only send the credentials given with the login and password options (as well as the local_cert option when using certificate authentication) on creating the client when invoking the service, not when fetching the WSDL (see here). There are two methods to overcome this problem:

  1. Add the login credentials to the WSDL url on the SoapClient constructor call

    $client = new SoapClient(
    'https://' . urlencode($login) . ':' . urlencode($password) . '@example.com/WSDL/nameofservice',
    array(
    'login' => $login,
    'password' => $password
    )
    );

    This should be the most simple solution - but in PHP Bug #27777 it is written that this won't work either (I haven't tried that).

  2. Fetch the WSDL manually using the HTTP stream wrapper or ext/curl or manually through your browser or via wgetfor example, store it on disk and instantiate the SoapClient with a reference to the local WSDL.

    This solution can be problematic if the WSDL document changes as you have to detect the change and store the new version on disk.

If no authentication dialog is shown and if you can read the WSDL in your browser, you should provide some more details to check for other possible errors/problems.

This problem is definitively not related to the service itself as SoapClient chokes already on reading the service descripion document before issuing a call to the service itself.

EDIT:

Having the WSDL file locally is a first step - this will allow the SoapClient to know how to communicate with the service. It doesn't matter if the WSDL is directly served from the service location, from another server or is read from a local file - service urls are coded within the WSDL so SoapClient always knows where to look for the service endpoint.

The second problem now is that SoapClient has no support for the WS-Security specifications natively, which means you must extend SoapClient to handle the specific headers. An extension point to add the required behaviour would be SoapClient::__doRequest() which pre-processes the XML payload before sending it to the service endpoint. But I think that implementing the WS-Security solution yourself will require a decent knowledge of the specific WS-Security specifications. Perhaps WS-Security headers can also be created and packed into the XML request by using SoapClient::__setSoapHeaders() and the appropriate SoapHeaders but I doubt that this will work, leaving the custom SoapClient extension as the lone possibility.

A simple SoapClient extension would be

class My_SoapClient extends SoapClient
{
protected function __doRequest($request, $location, $action, $version)
{
/*
* $request is a XML string representation of the SOAP request
* that can e.g. be loaded into a DomDocument to make it modifiable.
*/
$domRequest = new DOMDocument();
$domRequest->loadXML($request);

// modify XML using the DOM API, e.g. get the <s:Header>-tag
// and add your custom headers
$xp = new DOMXPath($domRequest);
$xp->registerNamespace('s', 'http://www.w3.org/2003/05/soap-envelope');
// fails if no <s:Header> is found - error checking needed
$header = $xp->query('/s:Envelope/s:Header')->item(0);

// now add your custom header
$usernameToken = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:UsernameToken');
$username = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:Username', 'userid');
$password = $domRequest->createElementNS('http://schemas.xmlsoap.org/ws/2002/07/secext', 'wsse:Password', 'password');
$usernameToken->appendChild($username);
$usernameToken->appendChild($password);
$header->appendChild($usernameToken);

$request = $domRequest->saveXML();
return parent::__doRequest($request, $location, $action, $version);
}
}

For a basic WS-Security authentication you would have to add the following to the SOAP-header:

<wsse:UsernameToken>
<wsse:Username>userid</wsse:Username>
<wsse:Password>password</wsse:Password>
</wsse:UsernameToken>

But as I said above: I think that much more knowledge about the WS-Security specification and the given service architecture is needed to get this working.

If you need an enterprise grade solution for the whole WS-* specification range and if you can install PHP modules you should have a look at the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP)



Related Topics



Leave a reply



Submit