引言
前一节介绍了使用userslst文件来实现webservice的用户名和密码的校验
本节介绍使用webservice的handler来实现webservice的安全校验
这里不用用户名和密码来实现安全校验换一种方式采用IP地址校验的方式
这里通过一个配置文件来控制是否打开IP校验开关以及允许哪些IP地址的客户端可以访问
这里的开发还是基于上一节HelloService这个基本的webservice基础上来开发
项目环境
system:win
myeclipse: tomcat: JDK:开发环境编译环境
axis:
项目结构图如下
示例代码配置文件
webxmlweb项目的配置文件和基本的webservice配置没任何区别
webxml
<?xml version= encoding=UTF?>
<webapp version=
xmlns=
xmlns:xsi=instance
xsi:schemaLocation=
app__xsd>
<servlet>
<servletname>AxisServlet</servletname>
<servletclass>
orgapacheaxistransporthttpAxisServlet
</servletclass>
</servlet>
<servletmapping>
<servletname>AxisServlet</servletname>
<urlpattern>/services/*</urlpattern>
</servletmapping>
</webapp>
serverconfigwsddaxis的配置文件这里的配置就是一个webservice+handler的基本配置
serverconfigwsdd
<?xml version= encoding=UTF?> <deployment xmlns= xmlns:java=> <globalConfiguration> <parameter name=sendMultiRefs value=pan/archive////true /> <parameter name=disablePrettyXML value=pan/archive////true /> <parameter name=adminPassword value=pan/archive////admin /> <parameter name=attachmentsDirectory value=pan/archive////file://localhost/D:/tomcat/webapps/WebService/WEBINF/attachments /> <parameter name=dotNetSoapEncFix value=pan/archive////true /> <parameter name=enableNamespacePrefixOptimization value=pan/archive////false /> <parameter name=sendXMLDeclaration value=pan/archive////true /> <parameter name=sendXsiTypes value=pan/archive////true /> <parameter name=attachmentsimplementation value=pan/archive////orgapacheaxisattachmentsAttachmentsImpl /> <requestFlow> <handler type=java:orgapacheaxishandlersJWSHandler> <parameter name=scope value=pan/archive////session /> </handler> <handler type=java:orgapacheaxishandlersJWSHandler> <parameter name=scope value=pan/archive////request /> <parameter name=extension value=pan/archive////jwr /> </handler> </requestFlow> </globalConfiguration> <handler name=LocalResponder type=java:orgapacheaxistransportlocalLocalResponder /> <handler name=URLMapper type=java:orgapacheaxishandlershttpURLMapper /> <handler name=Authenticate type=java:orgapacheaxishandlersSimpleAuthenticationHandler /> <service name=AdminService provider=java:MSG> <parameter name=allowedMethods value=pan/archive////AdminService /> <parameter name=enableRemoteAdmin value=pan/archive////false /> <parameter name=className value=pan/archive////orgapacheaxisutilsAdmin /> <namespace>;/namespace> </service> <service name=Version provider=java:RPC> <parameter name=allowedMethods value=pan/archive////getVersion /> <parameter name=className value=pan/archive////orgapacheaxisVersion /> </service> <transport name=http> <requestFlow> <handler type=URLMapper /> <handler type=java:orgapacheaxishandlershttpHTTPAuthHandler /> </requestFlow> <parameter name=qs:list value=pan/archive////orgapacheaxistransporthttpQSListHandler /> <parameter name=qs:wsdl value=pan/archive////orgapacheaxistransporthttpQSWSDLHandler /> <parameter name=qslist value=pan/archive////orgapacheaxistransporthttpQSListHandler /> <parameter name=thod value=pan/archive////orgapacheaxistransporthttpQSMethodHandler /> <parameter name=qs:method value=pan/archive////orgapacheaxistransporthttpQSMethodHandler /> <parameter name=qswsdl value=pan/archive////orgapacheaxistransporthttpQSWSDLHandler /> </transport> <transport name=local> <responseFlow> <handler type=LocalResponder /> </responseFlow> </transport> <! 配置一个handler用来进行IP校验> <handler name=IPHandler type=java:serverhandlerIpAuthentionHandler> <parameter name=status value=pan/archive////success /> </handler> <! 配置自己的服务 > <service name=HelloService provider=java:RPC> <parameter name=allowedMethods value=pan/archive////* /> <parameter name=className value=pan/archive////serverserviceHelloServiceImpl /> <! 引入IP校验的handler > <requestFlow> <handler type=IPHandler /> </requestFlow> </service> </deployment>
服务端文件
服务类
HelloServiceImpljava
HelloServiceImpljava
package serverservice; public class HelloServiceImpl {
public String hello(String s) {
Systemoutprintln(我是服务端……)
Systemoutprintln(方法的入参为+s)
return hello + s;
} }
handler处理类和配置文件
IpAuthentionHandlerjava
IpAuthentionHandlerjava
package serverhandler; import javaioIOException; import javaioInputStream; import javautilProperties; import javautilregexPattern; import javaxservlethttpHttpServletRequest; import orgapacheaxisAxisFault; import orgapacheaxisMessageContext; import orgapacheaxishandlersBasicHandler; import orgapacheaxistransporthttpHTTPConstants; import orgapacheaxisutilsMessages; //利用handler进行客户端IP校验 public class IpAuthentionHandler extends BasicHandler {
private static final long serialVersionUID = L;
private static Properties p = new Properties()
static {
InputStream in = null;
try {
//注意这里的文件的存放位置和文件路径的书写方式 path 不以/开头时默认是从此类所在的包下取资源
//这里如果我们把ipproperties放在src根目录下然后采用src/ipproperties的形式是没法取到此文件的
//此时需要使用
in=IpAuthentionHandlerclassgetClassLoader()getResourceAsStream(ipproperties)
in = IpAuthentionHandlerclassgetResourceAsStream(ipproperties)
pload(in)
} catch (IOException e) {
Systemoutprintln(ipproperties配置文件加载失败!)
eprintStackTrace()
} finally {
if (null != in)
try {
inclose()
} catch (IOException e) {
Systemoutprintln(关闭流操作发生异常!)
eprintStackTrace()
}
}
}
public void invoke(MessageContext messageContext) throws AxisFault {
String status=(String)thisgetOption(status)
Systemoutprintln(IpAuthentionHandlers status is :+status)
String uri = messageContextgetSOAPActionURI()
String targetService = messageContextgetTargetService()
Systemoutprintln(webservice开始IP认证service》 + uri + /+ targetService)
String name = HTTPConstantsMC_HTTP_SERVLETREQUEST;
HttpServletRequest request = (HttpServletRequest) messageContext
getProperty(name)
String remoteAddr = requestgetRemoteAddr()
Systemoutprintln(客户端IP: + remoteAddr)
String switcher = pgetProperty(ip_switcher)
Systemoutprintln(IP校验开关 + switcher)
if (onequalsIgnoreCase(switcher)) {
Systemoutprintln(服务端IP校验开关处于【打开】状态需要校验IP)
String regx = pgetProperty(ip_allow)
Systemoutprintln(允许调用服务的IP地址有 + regx)
if (null != regx && regxlength() > ) {
String regxArray[] = regxsplit()
boolean ip_check = false;
for (int i = ; i < regxArraylength; i++) {
Pattern p = pile(regxArray[i])
boolean flag = pmatcher(remoteAddr)find()
if (flag) {
ip_check = true;
break;
}
}
if (ip_check) {
Systemoutprintln(IP校验通过!)
} else {
throw new AxisFault(MessagesgetMessage(wrong ip:+remoteAddr)nullnull)
}
} else {
Systemoutprintln(请指定校验的客户端IP!)
throw new AxisFault()
}
} else if (offequalsIgnoreCase(switcher)) {
Systemoutprintln(服务端IP校验开关处于【关闭】状态不需要校验IP)
}
}
}
ipproperties
ipproperties
##################################IP校验配置################################## #IP校验开关 只能填写on或者off不区分大小写 ip_switcher=on #允许调用对应的webservice服务的客户端IP地址 多个IP地址之间用逗号隔开 #当ip校验开关打开的时候必须配置IP地址 ip_allow= ##################################IP校验配置##################################
客户端文件
Testjava
Testjava
package client;
import URL;
import javaxxmlrpcParameterMode;
import orgapacheaxisclientCall;
import orgapacheaxisencodingXMLType;
public class Test {
public static void main(String args[]) throws Exception {
webservice_user()
}
public static void webservice_user() throws Exception {
// 创建service对象通过axis自带的类创建
orgapacheaxisclientService service = new orgapacheaxisclientService()
// 创建url对象
String wsdlUrl = //localhost:/WebService_Security/services/HelloService?wsdl;// 请求服务的URL
URL url = new URL(wsdlUrl)// 通过URL类的构造方法传入wsdlUrl地址创建URL对象
// 创建服务方法的调用者对象call设置call对象的属性
Call call = (Call) servicecreateCall()
callsetTargetEndpointAddress(url)// 给call对象设置请求的URL属性
String serviceName = hello;// webservice的方法名
callsetOperationName(serviceName)// 给call对象设置调用方法名属性
calladdParameter(s XMLTypeXSD_STRING ParameterModeIN)// 给call对象设置方法的参数名参数类型参数模式
callsetReturnType(XMLTypeSOAP_STRING)// 设置调用方法的返回值类型
// callsetTimeout(new Integer())//设置超时限制
// 通过invoke方法调用webservice
String str = new String(pantp)
String dept = (String) callinvoke(new Object[] { str })// 调用服务方法
// 打印返回结果
Systemoutprintln(我是客户端……)
Systemoutprintln(dept)
} }
验证结果
发布工程启动tomcat服务器
看webservice在浏览器中是否可以正常显示
在浏览器中输入wsdl地址
//localhost:/WebService_Security/services/HelloService?wsdl
运行webservice客户端看是否可以正常的访问
目前IP配置文件中开关是打开的并且是允许访问此webservice服务的
运行后客户端和服务端日志分别如下
模拟不能正常访问的IP地址的调用情况
把ipproperties文件中的
ip_allow=
改为
ip_allow=
然后重新发布项目启动tomcat:
此时客户端和服务端的日志如下(此时需要时间稍微长一点客户端才会出现以下异常)