applicationContext.xml添加 <mvc:interceptors>
<bean class="com.jimubox.service.corperation.interceptors.APIRightAuthInterceptor"/> </mvc:interceptors> package com.jimubox.service.corperation.interceptors; import com.jimubox.service.basic.exceptions.ExceptionLogger; import com.jimubox.service.corperation.application.merchantkey.MerchantKeyCacheService; import com.jimubox.tools.net.IpAddressUtils; import com.jimubox.victory.ccp.utils.EncryptUtil; import com.jimubox.victory.helper.HttpHelper; import com.jimubox.victory.local.model.APIRightAuth; import com.jimubox.victory.util.HttpStatusCode; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by baojiawei on 4/16/2015. */ public class APIRightAuthInterceptor extends HandlerInterceptorAdapter { @Resource private MerchantKeyCacheService merchantKeyCacheService; private static String bad_signature_error = "Bad Signature"; private static String bad_parameter_error = "Bad Parameter"; private static String bad_timestamp_error = "Bad TimeStamp"; private static String bad_ip_error = "Invalid Access IP Address"; private static String block_ip_error = "Blocked Access IP Address"; private static String no_right = "Access Denied"; private Logger logger = LoggerFactory.getLogger(APIRightAuthInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler.getClass().isAssignableFrom(HandlerMethod.class)) { APIRightAuth apiRight = ((HandlerMethod) handler).getMethodAnnotation(APIRightAuth.class); if (apiRight == null) { return true; } else { try { //log access String mId = request.getParameter("merchantId"); String currentClientIp = HttpHelper.getRealIp(request); //request URL String url = request.getRequestURL().toString() + ((request.getQueryString() == null || request.getQueryString().toLowerCase().equals("null")) ? "" : ("?" + request.getQueryString())); logger.warn(String.format("商户:%s,IP:%s,访问地址:%s",mId, currentClientIp, url)); if(StringUtils.isBlank(request.getParameter("timeStamp")) || StringUtils.isBlank(request.getParameter("merchantId")) || StringUtils.isBlank(request.getParameter("token"))) { response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(bad_parameter_error.getBytes("utf-8")); return false; } long clientTime = Long.parseLong(request.getParameter("timeStamp")); long nowTime = System.currentTimeMillis(); //1.检查时间戳 if (nowTime - clientTime <= 180 * 1000 && nowTime - clientTime >= -180 * 1000) { int merchantId = Integer.parseInt(request.getParameter("merchantId")); //2.权限检查 if (merchantKeyCacheService.isMerchantAvailable(merchantId, apiRight.value().getValue())) { String ipAddressInDB = merchantKeyCacheService.getAccessIpAddress(merchantId, apiRight.value().getValue()); //3.IP白名单检查 if(StringUtils.isNotEmpty(ipAddressInDB)) { boolean isInRange = IpAddressUtils.isInRange(currentClientIp, ipAddressInDB); if (!isInRange) { logger.error(String.format("该访问IP不在白名单。商户:%s,IP:%s,访问地址:%s", mId, currentClientIp, url)); response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(bad_ip_error.getBytes("utf-8")); return false; } } //4.IP黑名单检查 String blockIpAddressInDB = merchantKeyCacheService.getBlockIpAddress(merchantId, apiRight.value().getValue()); if(StringUtils.isNotEmpty(blockIpAddressInDB)) { boolean isInRange = IpAddressUtils.isInRange(currentClientIp, blockIpAddressInDB); if (isInRange) { logger.error(String.format("该访问IP在黑名单。商户:%s,IP:%s,访问地址:%s", mId, currentClientIp, url)); response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(block_ip_error.getBytes("utf-8")); return false; } } //5.检查签名串 String key = merchantKeyCacheService.getKey(merchantId, apiRight.value().getValue()); String value = request.getParameter("merchantId") + "&" + request.getParameter("timeStamp") + "&" + key; EncryptUtil eu = new EncryptUtil(); if (!request.getParameter("token").equalsIgnoreCase(eu.md5Digest((value).toUpperCase()))) { response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(bad_signature_error.getBytes("utf-8")); return false; } else { return true; } } else{ //no right or invalid logger.error(String.format("没有访问权限。商户:%s,IP:%s,访问地址:%s",mId, currentClientIp, url)); response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(no_right.getBytes("utf-8")); return false; } } //time stamp error logger.error(String.format("时间戳验证失败。商户:%s,IP:%s,访问地址:%s",mId, currentClientIp, url)); response.setStatus(HttpStatusCode.BadRequest); response.getOutputStream().write(bad_timestamp_error.getBytes("utf-8")); return false; } catch (Exception e) { ExceptionLogger.log(e); response.setStatus(HttpStatusCode.InternalServerError); response.getOutputStream().write(bad_parameter_error.getBytes("utf-8")); logger.error(e.getMessage(), e); return false; } } } return true; } } package com.jimubox.victory.helper; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; public final class HttpHelper { public static final String ANDROID_SHORT_DESC = "android"; public static final String IOS_SHORT_DESC = "ios"; public static final String TOUCH_SHORT_DESC = "jimubox_touch"; public static final String UNKNOW_SHORT_DESC = "unknow"; public HttpHelper() { } public static String getRealIp(HttpServletRequest request) { String realRemoteIP = request.getHeader("x-forwarded-for"); String[] buff; if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getHeader("x-real-ip"); if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getHeader("x-touch-ip"); if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getRemoteAddr(); } return realRemoteIP; } public static String getRealIpForApp(HttpServletRequest request) { String realRemoteIP = request.getHeader("x-touch-ip"); String[] buff; if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getHeader("x-forwarded-for"); if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getHeader("x-real-ip"); if(StringUtils.isNotEmpty(realRemoteIP)) { buff = realRemoteIP.split(","); if(buff != null && buff.length > 0) { realRemoteIP = buff[0]; } } } if(StringUtils.isEmpty(realRemoteIP) || "unknown".equalsIgnoreCase(realRemoteIP)) { realRemoteIP = request.getRemoteAddr(); } return realRemoteIP; } public static boolean isMobileBrowser(HttpServletRequest request) { String u = request.getHeader("User-Agent"); Pattern patternb = Pattern.compile("(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", 10); Matcher matcherb = patternb.matcher(u); Pattern patternv = Pattern.compile("1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-", 10); Matcher matcherv = patternv.matcher(u.substring(0, 4)); return matcherb.find() || matcherv.find(); } public static String getDeviceShortDesc(HttpServletRequest request) { if(request.getHeader("User-Agent") != null) { String userAgent = request.getHeader("User-Agent").toLowerCase(); if(userAgent.contains("android")) { return "android"; } if(userAgent.startsWith("ios")) { return "ios"; } if(userAgent.contains("jimubox_touch")) { return "jimubox_touch"; } } return "unknow"; } public static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookieSources = request.getCookies(); if(cookieSources == null) { return null; } else { Cookie[] arr$ = cookieSources; int len$ = cookieSources.length; for(int i$ = 0; i$ < len$; ++i$) { Cookie cookieSource = arr$[i$]; if(StringUtils.isNotEmpty(name) && name.equals(cookieSource.getName())) { return cookieSource; } } return null; } } } |
|
来自: dabinglibrary > 《Spring》