PHP webservice 身份认证 客户端与服务端实现

note:本文转自何俊斌先生 的博客。但窃自以为有点小错误:function authenticate自己略作修改。找了一整天,原来服务端没什么特别要做的,就是像普通的webservice一样提供方法就可以。

下面是客户端的实现:
class authentication_header { private $username; private $password; public function __construct($username, $password) { $this->username = $username; $this->password = $password; } } // generate new object $auth = new authentication_header('123', '123'); // create authentication header values $authvalues = new SoapVar($auth, SOAP_ENC_OBJECT, 'authenticate'); // generate header $header = new SoapHeader('http://78diy.org/', 'authenticate', $authvalues); $client = new SoapClient('http://127.0.0.1:8000/webservice/test/serve.php?wsdl'); $client->__setSoapHeaders(array($header)); echo $client->__soapCall('felineResponse', array()); ?>
如下是服务器端的实现:
username = $value->username; $this->password = $value->password; if($this->username == '123'&& $this->password=='123' ) { $this->Authenticated = true; } else { $this->Authenticated = false; } } /* * Test method */ public function felineResponse(){ // Place this at the start of every exposed method // This is because the SoapServer will attempt to call // if no authentication headers are passed. if($this->Authenticated){ return 'zheng que'; } else { return 'cuo wu'; } } } // Instantiate server with relevant wsdl & class. $server = new SoapServer( 'mysoapwsdl.wsdl' ); $server->setClass('mysoapclass'); $server->handle(); ?>

有人 可能想直接传递包含用户名和密码的数组进行验证 其实,也是可以的

把客户端

$authvalues =array('username'=>'admin','pwd'=>'123456');

改成这样,则传递的则是对象数组

object(stdClass)#4 (1) { ["item"]=> array(2) { [0]=> object(stdClass)#5 (2) { ["key"]=> string(8) "username" ["value"]=> string(5) "admin" } [1]=> object(stdClass)#6 (2) { ["key"]=> string(3) "pwd" ["value"]=> string(6) "123456" } } }

 

 大家看到了吧

若想在服务端验证 则需稍作修改

 

$this->username = $value->item[0]->value;; $this->password = $value->item[1]->value;

后续 :上面那种方式传数组有点麻烦实际上改成这样更方便

$auth = array('username'=>'admin', 'password'=>'123456');

 

这样服务端无需修改代码,他同样会被当作一个对象来处理

至于原因,我也不甚清楚,希望高人指点。

由于本人php还是比较弱,如有错误之处欢迎指正

你可能感兴趣的:(PHP)