package com.hgq.cxf.ip.interceptor;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class CxfIpInterceptor extends AbstractPhaseInterceptor<Message>
{
private static final Logger log = Logger.getLogger(CxfIpInterceptor.class);
public CxfIpInterceptor()
{
super(Phase.RECEIVE);
}
// 允许访问的IP
private List<String> allowIpList;
// 拒绝访问的IP
private List<String> deniedList;
public List<String> getAllowIpList()
{
return allowIpList;
}
public List<String> getDeniedList()
{
return deniedList;
}
public void setAllowIpList(List<String> allowIpList)
{
this.allowIpList = allowIpList;
}
public void setDeniedList(List<String> deniedList)
{
this.deniedList = deniedList;
}
@Override
public void handleMessage(Message msg) throws Fault
{
// 获取WS请求中的IP
HttpServletRequest request = (HttpServletRequest) msg.get(AbstractHTTPDestination.HTTP_REQUEST);
String ip = request.getRemoteAddr();
// 判断是否在拒绝列表中
if(null != deniedList && !deniedList.isEmpty())
{
for(String deniedIp : deniedList)
{
if(ip.equals(deniedIp))
{
if(log.isEnabledFor(Level.WARN))
{
log.warn("IP:" + ip + "在拒绝访问列表中");
}
throw new Fault(new IllegalAccessException("IP:[" + ip + "]拒绝访问,请联系管理员"));
}
}
}
// 判断是否在允许访问列表中
if(null != allowIpList && !allowIpList.isEmpty())
{
for(String allowIp : allowIpList)
{
if(ip.equals(allowIp))
{
if(log.isEnabledFor(Level.WARN))
{
log.warn("IP:" + ip + "在允许列表中,允许访问");
}
break;
}
else
{
if(log.isEnabledFor(Level.WARN))
{
log.warn("IP:" + ip + "不在允许访问列表中");
}
throw new Fault(new IllegalAccessException("IP:[" + ip + "]拒绝访问,请联系管理员"));
}
}
}
}
}
评论0
最新资源