http接口安全校验


@Component
public class MassageInterceptor implements HandlerInterceptor {

private static final Logger log = LoggerFactory.getLogger(MassageInterceptor.class);

/**
* 进入controller层之前拦截请求
*
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// 计算校验值 是否与cs匹配
String bodyJson = httpServletRequest.getAttribute("postParameter").toString();
String cs = httpServletRequest.getParameter("cs");
String openkey = "RIqXkbml6dunptIc";
String openid = httpServletRequest.getParameter("openid");
String ts = httpServletRequest.getParameter("ts");
if (StringUtils.isEmpty(openid)) {
errorResponse(httpServletResponse, "openid不能为空");
return false;
}

if (StringUtils.isEmpty(ts)) {
errorResponse(httpServletResponse, "时间戳不能为空");
return false;
}
StringBuilder csBuilder = new StringBuilder()
.append("Data[").append(bodyJson).append("];")
.append("openid[").append(openid).append("];")
.append("openkey[").append(openkey).append("];")
.append("ts[").append(ts).append("];");
//logger.info("MD5加密字符串:{}", csBuilder.toString());
if (!cs.equals(MD5Util.md5(csBuilder.toString()))) {
exceptionResponse(httpServletResponse, "CS验证不通过");
return false;
}
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
// log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//log.info("---------------视图渲染之后的操作-------------------------0");
}

private void errorResponse(HttpServletResponse response, String errorMsg) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
HttpResult resultMsg = new HttpResult();
resultMsg.setCode(HttpResultConstant.HTTP_ERROR);
resultMsg.setMsg(errorMsg);
JSONObject obj = JSONObject.fromObject(resultMsg);
out.append(obj.toString());
log.info("接口响应:{}", obj.toString());
}

private void exceptionResponse(HttpServletResponse response, String errorMsg) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
HttpResult resultMsg = new HttpResult();
resultMsg.setCode(HttpResultConstant.HTTP_EXCEPTION);
resultMsg.setMsg(errorMsg);
JSONObject obj = JSONObject.fromObject(resultMsg);
out.append(obj.toString());
log.info("接口响应:{}", obj.toString());
}

}
posted @ 2020-04-27 16:00  那光芒很刺眼  阅读(935)  评论(0编辑  收藏  举报