webservice服务增加header认证

wevservice服务没有认证不是很安全,如果是单独端口还可以加防火墙限制.

这里使用UUID+密码的MD5来传输,避免密码的泄漏,客户端发送header会调用对应方法,服务端增加是否取得认证的属性,从而判断是否用合法用户。

下面是服务端

 

class service
{
    //是否认证
    private $authorized = false;

    //用户名
    private $user = "admin";

    //密码
    private $pass = "admin";

    //认证
    function RequestSOAPHeader($header)
    {
        if ($header->username== $this->user) {
            if (md5($header->tid.$this->pass) == $header->password) {
                $this->authorized = true;
            }
        }
    }
 /*
    取得位置信息
    */
    function test()
    {
        if (!$this->authorized) {
            return array('status'=>"0","data"=>"没有通过认证");
        }
        return array('status'=>"1","data"=>"ok");
    }
}
$server=new SoapServer(null,array('uri' => "http://www.linuxphp.org/"));
$server->setClass("service");
$server->handle();

 

下面给出客户端

 

//保存用户名和密码的载体
class SoapUserInfo {
    /**
      用户名
     */
    public $username;
    /**
      加密的密码
     */
    public $password;
    /*
       唯一UUID
     */
    public $tid;
    public function __construct($u, $p) {
        $this->tid = $this->uuid();
        $this->password = md5($this->tid.$p);
        $this->username = $u;
    }
    function uuid()
    {
        // version 4 UUID
        return sprintf(
                '%08x%04x%04x%02x%02x%012x',
                mt_rand(),
                mt_rand(0, 65535),
                bindec(substr_replace(
                        sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
                    ),
                bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
                mt_rand(0, 255),
                mt_rand()
                );
    }
}
//webservice服务地址
$location = "http://www.example.com/api/soap";
$soap = new SoapClient(null,array(
            "location" => $location,
            "uri"      => '',
            "style"    => SOAP_RPC,
            "use"      => SOAP_ENCODED
           ));
//这的RequestSOAPHeader一定要和服务端对应起来
$header = new SoapHeader("http://www.linuxphp.org", 'RequestSOAPHeader'
                       , new SoapUserInfo('admin', 'admin'));
$soap->__setSoapHeaders(array($header));
try {
    $data = $soap->test();
    var_dump($data);
} catch (SoapFault $e) {
    var_dump($e);
}

 

Tags: header , webservice

上一篇: FLASH文件上传失败与代理   下一篇: 极利恒河 CMPP2 MSGID反解JAVA和PHP版本

提交疑问

回顶部