cxf中自定义拦截器限制IP
- - jackyrong// 通过一个IpAddressConfig对象,从XML文件中读取预先设置的允许和拒绝的IP地址,这些值也可以来自数据库. IpAddressConfig config = IpAddressConfig.getInstance(); // 获取config实例. List allowedList = config.getAllowedList(); // 允许访问的IP地址.
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; /** * IP地址拦截器 * 可在filter.xml文件中配置允许和拒绝访问的IP地址 * @author Sunshine * */ public class IpAddressInInterceptor extends AbstractPhaseInterceptor<Message> { public IpAddressInInterceptor() { super(Phase.RECEIVE); } public void handleMessage(Message message) throws Fault { HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); // 通过一个IpAddressConfig对象,从XML文件中读取预先设置的允许和拒绝的IP地址,这些值也可以来自数据库 IpAddressConfig config = IpAddressConfig.getInstance(); // 获取config实例 List<String> allowedList = config.getAllowedList(); // 允许访问的IP地址 List<String> deniedList = config.getDeniedList(); // 拒绝访问的IP地址 String ipAddress = request.getRemoteAddr(); // 取客户端IP地址 // 先处理拒绝访问的地址 for (String deniedIpAddress : deniedList) { if (deniedIpAddress.equals(ipAddress)) { throw new Fault(new IllegalAccessException("IP address " + ipAddress + " is denied")); } } // 如果允许访问的集合非空,继续处理,否则认为全部IP地址均合法 if (allowedList.size() > 0) { boolean contains = false; for (String allowedIpAddress : allowedList) { if (allowedIpAddress.equals(ipAddress)) { contains = true; break; } } if (!contains) { throw new Fault(new IllegalAccessException("IP address " + ipAddress + " is not allowed")); } } } }
<!-- IP地址输入拦截器 --> <bean id="ipAddressInInterceptor" class="com.yourcompany.ws.interceptor.IpAddressInInterceptor" /> <!-- 用户名和密码输入拦截器 --> <bean id="wss4jInInterceptor" class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor"> <property name="properties"> <map> <entry key="action" value="UsernameToken Timestamp" /> <entry key="passwordType" value="PasswordDigest" /> <entry key="passwordCallbackRef" value-ref="digestPasswordCallback" /> </map> </property> </bean> <!-- 密码回调 --> <bean id="digestPasswordCallback" class="com.yourcompany.ws.handler.DigestPasswordCallback" /> <!-- 全局Bus(输入拦截器) --> <cxf:bus> <cxf:inInterceptors> <ref bean="ipAddressInInterceptor" /> <ref bean="wss4jInInterceptor" /> </cxf:inInterceptors> </cxf:bus> <!-- WebService服务 --> <jaxws:endpoint id="helloWorldServiceEP" address="/HelloWorldService"> <jaxws:implementor ref="helloWorldService" /> </jaxws:endpoint> <bean id="helloWorldService" class="com.yourcompany.ws.impl.HelloWorldServiceImpl" />