用Spring MVC做api接口,在请求中加入token做简单的验证
服务器:
拼接token之外所有参数,最后拼接token_key,做MD5,与token参数比对
如果token比对失败返回状态码 500
public class APIInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
Log.info(request);
String token = request.getParameter("token");
// token is not needed when debug
if(token == null) return true; // !! remember to comment this when deploy on server !!
Enumeration paraKeys = request.getParameterNames();
String encodeStr = "";
while (paraKeys.hasMoreElements()) {
String paraKey = (String) paraKeys.nextElement();
if(paraKey.equals("token"))
break;
String paraValue = request.getParameter(paraKey);
encodeStr += paraValue;
}
encodeStr += Default.TOKEN_KEY;
Log.out(encodeStr);
if ( ! token.equals(DigestUtils.md5Hex(encodeStr))) {
response.setStatus(500);
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
Log.info(request);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
客户端:
拼接请求接口的所有参数,最后拼接token_key,做MD5,作为token参数
请求样例:http://127.0.0.1:8080/interface/api?key0=param0&key1=param1&token=md5(concat(param0, param1))
API test
Search:
token_key
md5 {{md5(str)}}