mikeobrien.net Curriculum Vitae Blog Labs
Tuesday, April 07, 2009

Adding a WSS UsernameToken with the native PHP SoapClient is pretty straight forward (Mind you, this is just the plain text credentials so you should use transport security). Here is the usage:

$wsdl = "https://services.yada.net/Yada.svc?wsdl";

// Or 'soap_version' => SOAP_1_1 if your using SOAP 1.1
$options = array(
    'location' => 'https://services.yada.net/Yada.svc',
    'soap_version' => SOAP_1_2);

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

// Add the WSS username token headers
AddWSSUsernameToken($client, 'tony', 'clifton');

try
{
    $client->GetVersion();

    echo str_replace('>', '&gt;<br/>', 
        str_replace('<', '&lt;', 
            str_replace('&', '&amp;', 
                $client->__getLastResponse())));
}
catch(Exception $e)
{
    echo $e;
}

Here is the implementation:

function AddWSSUsernameToken($client, $username, $password)
{
    $wssNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
    
    $username = new SoapVar($username, 
                            XSD_STRING, 
                            null, null, 
                            'Username', 
                            $wssNamespace);
                            
    $password = new SoapVar($password, 
                            XSD_STRING, 
                            null, null, 
                            'Password', 
                            $wssNamespace);
    
    $usernameToken = new SoapVar(array($username, $password), 
                                    SOAP_ENC_OBJECT, 
                                    null, null, 'UsernameToken', 
                                    $wssNamespace);
                            
    $usernameToken = new SoapVar(array($usernameToken), 
                            SOAP_ENC_OBJECT, 
                            null, null, null, 
                            $wssNamespace);
    
    $wssUsernameTokenHeader = new SoapHeader($wssNamespace, 'Security', $usernameToken);
    
    $client->__setSoapHeaders($wssUsernameTokenHeader); 
}
Tuesday, April 07, 2009 1:26:04 PM (GMT Daylight Time, UTC+01:00)  #   |  Comments [0]  |  Trackback
Creative Commons License