Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate non-wsdl soap in PHP

Tags:

php

soap

I used this way to get data from server to client side. but I have a problem to authenticate server files.

I want to check username and password before give permission to read data. I tried to that using an extra method but I it doesn't work.

server

class MyService
{
    public function add($x, $y)
    {
        return $x + $y;
    }
}

$options = array(
    'uri' => 'http://server/namespace',
    'location' => 'http://server/location',
);

$server = new SOAPServer(null, $options);
$server->setObject(new MyService());
$server->handle();

client side

$options = array(
    'uri' => 'http://server/namespace',
    'location' => 'http://server/location',
);
$client = new SOAPClient(null, $options);
echo $client->add(10, 10);
like image 877
Mak Avatar asked Jul 31 '15 17:07

Mak


2 Answers

If you can live with a hard-coded username and password and HTTP basic authentication, then you can put the following code on top of the server file:

if (! isset($_SERVER['PHP_AUTH_USER']) ||
    $_SERVER['PHP_AUTH_USER'] !== 'foo' ||
    $_SERVER['PHP_AUTH_PW'] !== 'bar') { 
  header('WWW-Authenticate: Basic realm="My service"');
  header('HTTP/1.1 401 Unauthorized');
  echo 'Unauthorized';
  exit;
} 

This checks whether HTTP authentication data is present, and if not, will send an HTTP 401 error back to the client. If authentication data is present, it will be validated against the hard-coded username foo and password bar.

In order to pass username/password from the client script, adjust $options in the client as follows:

$options = array(
  'uri' => 'http://server/namespace',
  'location' => 'http://server/location',
  'login' => 'foo',     // username
  'password' => 'bar'   // password
);
$client = new SOAPClient(null, $options);

Please note that HTTP basic authentication is the simplest to set up, but that username and password will be transferred to the server in quasi plain text. You should therefore at least use SSL for the service endpoint, so all communication gets encrypted.

HTTP digest authentication is more secure, as it will only send hashes of the credentials, but it requires a bit more work to set up. A good starting point is the HTTP authentication page in the PHP manual.

For validating the received username/password data on the server side, you may also want to use a database with valid usernames/passwords/login tokens instead of the hard-coded credentials from the example.

like image 63
stj Avatar answered Oct 07 '22 17:10

stj


Why not send the username+pass as a parameter in the soap. On the server side you should have a base object that has all the authentication logic and have "MyService" inherit that. The base object will always handle the request and then pass on the details to MyService if it passes authentication.

like image 23
in need of help Avatar answered Oct 07 '22 15:10

in need of help