Spring MVC Interceptor 拦截器 api接口 简单token验证

用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 {
		
	}
}

spring-config.xml配置中加入
	
		
			
			
		
	


客户端:

拼接请求接口的所有参数,最后拼接token_key,做MD5,作为token参数

请求样例:http://127.0.0.1:8080/interface/api?key0=param0&key1=param1&token=md5(concat(param0, param1))


api测试页面,用到了Bootstrap和AngularJS,还有一个js的hex_md5函数



	
	API test
	
	
	
	



	
Search:
token_key md5 {{md5(str)}}

{{api.request(api.params, value0, value1, value2, value3, value4, value5, value6, value7, value8, value9)}}
{{concat(value0, value1, value2, value3, value4, value5, value6, value7, value8, value9)}}
{{api.params[0]}} {{api.params[1]}} {{api.params[2]}} {{api.params[3]}} {{api.params[4]}} {{api.params[5]}} {{api.params[6]}} {{api.params[7]}} {{api.params[8]}} {{api.params[9]}} token




你可能感兴趣的:(Spring MVC Interceptor 拦截器 api接口 简单token验证)