views:

3590

answers:

3

I am trying to connect to a Web Service which is password protected and the url is https. I can't figure out how to authenticate before the script makes a request. It seems like it makes a request as soon as I define the service. For instance, if I put in:

$client = new SoapClient("https://example.com/WSDL/nameofservice",
       array('trace' => 1,)
);

and then go to the site on the browser, I get:

Fatal error: Uncaught SoapFault exception: 
[WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from
'https://example.com/WSDL/nameofservice' in /path/to/my/script/myscript.php:2 
Stack trace: #0 /path/to/my/script/myscript.php(2): 
SoapClient->SoapClient('https://example...', Array) #1 {main} thrown in 
/path/to/my/script/myscript.php on line 2

If I try defining the service as a Soap Server, like:

$server= new SoapServer("https://example.com/WSDL/nameofservice");

I get:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt;
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>WSDL</faultcode>
<faultstring>
SOAP-ERROR: Parsing WSDL: 
Couldn't load from 'https://example.com/WSDL/nameofservice'
</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I haven't tried sending a raw request envelope yet to see what the server returns, but that may be a workaround. But I was hoping someone could tell me how I can set it up using the php built-in classes. I tried adding "userName" and "password" to the array, but that was no good. The problem is that I can't even tell if I'm reaching the remote site at all, let alone whether it is refusing the request.

A: 

$client = new SoapClient("some.wsdl", array('login' => "some_name", 'password' => "some_password"));

From the php documentation

nullptr
That was the first thing I did, same error, as I recall. The authentication goes into the header (according to the documentation for this specific service), and I don't think I can change the header until after defining the client, but by then, the error is thrown.
Anthony
+9  A: 

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)

Stefan Gehrig
Wow. Thanks for a great head start. Okay, so to be more specific, it is not an http authentication. If I go the url, I get redirected to login, then I can see the service. In the documentation for this service, it says that user authentication should be set in the SOAP header, but obviously I'm seeing how to do that in PHP. (this is called WS-security, going on my last google search, and it's not well implemented in PHP it seems.) If you know of a way to set the header, or use another method, like curl, to get the service and then passing that to the SoapClient, that would be enlightening.
Anthony
Oh! Quick question... So I copied the service to a file on my server, I'm able to set it up. I'm still unclear how to actually get around in it. But were you saying that the service will work when it's not in its actual location?
Anthony
Extended the answer with some points on WS-Security and SOAP-request manipulation with SoapClient.
Stefan Gehrig
You definitely get the answer cred on this one, thanks! I have been messing with it a bit. I added a SoapHeader array, using the authentication block's parameters. Not sure if it will stick, but it didn't throw an error. To be honest, I was in a panic to connect to the service because I have no idea how WSDL/SOAP/Webservices work at all and I couldn't get my hands dirty until I had the connection. I'll let you know if the SoapHeader is enough. Thanks again!
Anthony
A: 

I have more simple solution than extending the existing soapclient library.

Step1: Create two classes to create a structure for WSSE headers

class clsWSSEAuth {
private $Username;
private $Password;
function __construct($username, $password) {
$this->Username=$username;
$this->Password=$password;
}
}

class clsWSSEToken {
private $UsernameToken;
function __construct ($innerVal){
$this->UsernameToken = $innerVal;
}
}

Step2: Create Soap Variables for UserName and Password

    $username = 1111;
    $password = 1111;

//Check with your provider which security name-space they are using.
$strWSSENS = "http://schemas.xmlsoap.org/ws/2002/07/secext";

$objSoapVarUser = new SoapVar($username, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS);
$objSoapVarPass = new SoapVar($password, XSD_STRING, NULL, $strWSSENS, NULL, $strWSSENS);

Step3: Create Object for Auth Class and pass in soap var

$objWSSEAuth = new clsWSSEAuth($objSoapVarUser, $objSoapVarPass);

Step4: Create SoapVar out of object of Auth class

$objSoapVarWSSEAuth = new SoapVar($objWSSEAuth, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);

Step5: Create object for Token Class

$objWSSEToken = new clsWSSEToken($objSoapVarWSSEAuth);


Step6: Create SoapVar out of object of Token class
$objSoapVarWSSEToken = new SoapVar($objWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'UsernameToken', $strWSSENS);

Step7: Create SoapVar for 'Security' node

$objSoapVarHeaderVal=new SoapVar($objSoapVarWSSEToken, SOAP_ENC_OBJECT, NULL, $strWSSENS, 'Security', $strWSSENS);

Step8: Create header object out of security soapvar

$objSoapVarWSSEHeader = new SoapHeader($strWSSENS, 'Security', $objSoapVarHeaderVal,true, 'http://abce.com');

//Third parameter here makes 'mustUnderstand=1
//Forth parameter generates 'actor="http://abce.com"'

Step9: Create object of Soap Client

$objClient = new SoapClient($WSDL, $arrOptions);

Step10: Set headers for soapclient object

$objClient->__setSoapHeaders(array($objSoapVarWSSEHeader));

Step 11: Final call to method

$objResponse = $objClient->__soapCall($strMethod, $requestPayloadString);
Bhargav Khatana