php webservice 客户端ip,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());

?>

如下是服务器端的实现:

class mysoapclass {

/*

* Authentication function

* This is called by the Soap header of the same name. The function name is a Ws-security standard auth tag

* and corresponds to the header tag.

*

* @param string username

* @param string password

*/

public function authenticate($value){

// Store username for logging

$this->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还是比较弱,如有错误之处欢迎指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值