PHP中使用SoapServer来创建Web Service进行权限验证的两种方法:soap头验证,http头验证。
1.soap头验证
1.soap头验证
class test{
var $is_login = false;
function auth($key){
//if($key!='123') throw new SoapFault("auth failed", "123");
$this->is_login = $key==123;
}
function add($a,$b){
//$this->auth();
if($this->is_login){
return $a+$b;
}else{
return -1;
}
}
}
$server = new SoapServer(null,array('uri'=>'http://localhost/service'));
$server->setClass("test");
$server->handle();
访问时以axis2为例.
public class Test {
public static void main(String[] args) throws Exception{
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
client.addStringHeader(new QName("ns","auth"), "123");//通过soap进行验证
options.setTo(new EndpointReference("http://localhost/server.php"));
Object[] para = new Object[]{1,2};
QName name = new QName("http://localhost/service", "add");
OMElement om = client.invokeBlocking(name,para);
OMNode node = (OMNode)om.getChildren().next();
Integer rs = (Integer) BeanUtil.processObject((OMElement)node, Integer.class, null, true, new DefaultObjectSupplier());
System.out.println(rs);
}
}
2.通过http头
server.php
function add($a,$b){
return $a+$b;
}
$server = new SoapServer(null,array('uri'=>'http://localhost/service'));
$server->addFunction(add);
if($_SERVER['PHP_AUTH_USER']!='user'){
$server->fault("1", "aaa");
}
$server->handle();
调用
public class Test {
public static void main(String[] args) throws Exception{
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
Authenticator auth = new Authenticator();
auth.setPreemptiveAuthentication(true);
auth.setUsername("user");
auth.setPassword("add");
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setTo(new EndpointReference("http://localhost/server.php"));
Object[] para = new Object[]{1,2};
QName name = new QName("http://localhost/service", "add");
OMElement om = client.invokeBlocking(name,para);
OMNode node = (OMNode)om.getChildren().next();
Integer rs = (Integer) BeanUtil.processObject((OMElement)node, Integer.class, null, true, new DefaultObjectSupplier());
System.out.println(rs);
}
}