1. 程式人生 > >spring-cloud 之對 FeignClient 請求頭做處理

spring-cloud 之對 FeignClient 請求頭做處理

業務場景:系統採用了spring-cloud架構,目前分兩層,1:資料展示層,2:資料連線層,為了分層清晰,我們在第一層完成使用者鑑權,第二層只做單純的介面呼叫。為了防止第二層介面因為某些原因,暴露出去造成惡意呼叫,所以我們需要對第一層的FeignClient的請求頭做一次處理,帶上一個類似Token令牌的東西來訪問資料連線層!然後在到資料連線層去通過攔截器來判斷從一層傳來的請求是否合法!

實現方案:

1.首先需要實現RequestInterceptor這個介面

@Configuration
public class MyRequestInterceptor implements RequestInterceptor {
	
	
	

	@Autowired
	private ResourceUtil resourceUtil;
	
	@Override
	public void apply(RequestTemplate requestTemplate) {
		
		TSUser loginUser = resourceUtil.getSessionUser();
		Map<STRING,Object> wechatUserInfo = resourceUtil.getStoreUserInfo(NULL);
		Map<STRING,Object> requestParam = NEW TreeMap<STRING,Object>();
		IF(loginUser != NULL) {
			requestTemplate.header("operatorId", loginUser.getId()+"");
			requestTemplate.header("visable", loginUser.getVisable());
			requestParam.put("operatorId", loginUser.getId()+"");
			requestParam.put("visable", loginUser.getVisable());
		}

		STRING url = requestTemplate.url();
		STRING TIMESTAMP = System.currentTimeMillis()+"";
		requestTemplate.header("url", url+"");
		requestTemplate.header("timestamp",TIMESTAMP);
		requestParam.put("url", url);
		requestParam.put("timestamp", TIMESTAMP);
		requestTemplate.header("sign", TokenUtil.createSign(requestParam));
	
		
	}
	

}

以上程式碼可以看出,我針對請求頭設了一些公用引數,然後用那些引數構造了一個sign出來,然後到資料鏈接層去做校驗該請求是否為合法請求!

2.在資料連線層的微服務中實現HandlerInterceptor(攔截器)

@Configuration
public class RequestVerifyInterceptor implements HandlerInterceptor{

	
	
	public RequestVerifyInterceptor() {

	}
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		String sign = request.getHeader("sign");
		String operatorId = request.getHeader("operatorId");
		String visable = request.getHeader("visable");
		String timestamp = request.getHeader("timestamp");
		String url = request.getHeader("url");
		Map<String,Object> requestHeaderMap = new TreeMap<String,Object>();
		requestHeaderMap.put("timestamp", timestamp);
		requestHeaderMap.put("operatorId", operatorId);
		requestHeaderMap.put("visable", visable);
		requestHeaderMap.put("url", url);
		String signR = TokenUtil.createSign(requestHeaderMap);
		if(sign == null || !sign.equals(signR)) {
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().print(JSON.toJSONString(ResponseObj.returnError("非法請求")));
			return false;
		}
			
		
  		return true;
	}

}

攔截器裡面把第一層設定到請求頭裡面的引數全部拿出來,然後在構造出一個sign對比是否一樣,不一樣則表示是非法請求!