需求背景:与客户端通信内容需要加密。客户端将请求参数进行加密,服务端对响应结果进行加密。
那么对于后端而言,最方便的就是在过滤器里面对请求、响应进行统一处理了。这里需要涉及到HttpServletRequestWrapper与HttpServletResponseWrapper。
【1】非json请求处理
如下所示ParameterRequestWrapper 继承自HttpServletRequestWrapper ,重写获取参数的方法。
/** * Created by jianggc at 2022/4/5. */ public class ParameterRequestWrapper extends HttpServletRequestWrapper { private Map<String , String[]> params = new HashMap<String, String[]>(); @SuppressWarnings("unchecked") public ParameterRequestWrapper(HttpServletRequest request) { // 将request交给父类,以便于调用对应方法的时候,将其输出 super(request); //将参数表,赋予给当前的Map以便于持有request中的参数 this.params.putAll(request.getParameterMap()); } //重载一个构造方法 public ParameterRequestWrapper(HttpServletRequest request , Map<String , Object> extendParams) { this(request); addAllParameters(extendParams);//这里将扩展参数写入参数表 } @Override public String getParameter(String name) {//重写getParameter,代表参数从当前类中的map获取 String[]values = params.get(name); if(values == null || values.length == 0) { return null; } return values[0]; } @Override public Enumeration<String> getParameterNames() { return new Vector(params.keySet()).elements(); } @Override public String[] getParameterValues(String name) { String[] values = params.get(name); if (values == null || values.length == 0) { return null; } return values; } public void addAllParameters(Map<String , Object>otherParams) {//增加多个参数 for(Map.Entry<String , Object>entry : otherParams.entrySet()) { addParameter(entry.getKey() , entry.getValue()); } } public void addParameter(String name , Object value) {//增加参数 if(value != null) { if(value instanceof String[]) { params.put(name , (String[])value); }else if(value instanceof String) { params.put(name , new String[] {(String)value}); }else { params.put(name , new String[] {String.valueOf(value)}); } } } }
上面给了入口方法addAllParameters让你可以放入需要的数据。这个操作是在过滤器里面处理的。
由于与客户端协商了参数传递方式为params=encrypt(userName=jane&mobile=13813813800),所以这里我们对params进行处理,回复为springboot喜欢的格式。
/** * Created by jianggc at 2022/4/5. */ @WebFilter(urlPatterns={"/*"}) public class RequestAesFilter implements Filter { private static final Logger logger= LoggerFactory.getLogger(RequestAesFilter.class); @Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 获取request HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String params = httpServletRequest.getParameter("params"); Map<String,Object> parmMap= new HashMap<>(); if(!StringUtils.isEmpty(params)){ try { String decryptBase64 = AesUtils.decryptBase64(params, AesUtils.aesKey); String[] split = decryptBase64.split("&"); for(String entry:split){ String[] strings = entry.split("="); parmMap.put(strings[0],strings[1]); } } catch (Exception e) { logger.error(e.getMessage(),e); } } logger.debug("解密后的parmMap:{}",parmMap); ParameterRequestWrapper pr = new ParameterRequestWrapper(httpServletRequest, parmMap); chain.doFilter(pr, response); } }
【2】响应处理
这里ResponseWrapper继承自HttpServletResponseWrapper提供了写入和读取的方法。
public class ResponseWrapper extends HttpServletResponseWrapper { // 真正缓存数据的流 private ByteArrayOutputStream byteArrayOutputStream = null; private ServletOutputStream servletOutputStream = null; private PrintWriter writer = null; public ResponseWrapper(HttpServletResponse response) { super(response); // TODO Auto-generated constructor stub byteArrayOutputStream = new ByteArrayOutputStream(); servletOutputStream = new WrapperOutputStream(byteArrayOutputStream); writer = new PrintWriter(byteArrayOutputStream); } /** * 当获取字节输出流时,实际获取的是我们自己包装的字节输出流 */ public ServletOutputStream getOutputStream() { return servletOutputStream; } /** * 当获取字符输出流时,实际获取的是我们自己包装的字符输出流 */ public PrintWriter getWriter() { return writer; } public void flushBuffer() throws IOException { if (servletOutputStream != null) { servletOutputStream.flush(); } if (writer != null) { writer.flush(); } } public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap(0); Iterator var3 = this.getHeaderNames().iterator(); while(var3.hasNext()) { String headerName = (String)var3.next(); headers.put(headerName, this.getHeader(headerName)); } return headers; } public byte[] getResponseData() throws IOException { flushBuffer(); return byteArrayOutputStream.toByteArray(); } public String getContent() throws IOException { flushBuffer(); return byteArrayOutputStream.toString(); } } class WrapperOutputStream extends ServletOutputStream { private ByteArrayOutputStream baos; public WrapperOutputStream(ByteArrayOutputStream out) { super(); this.baos = out; } public boolean isReady() { return true; } public void write(int b) throws IOException { this.baos.write(b); } public void write(byte[] b) throws IOException { this.baos.write(b); } public void write(byte[] b, int off, int len) throws IOException { this.baos.write(b, off, len); } public String getContent() { return this.baos.toString(); } public byte[] toByteArray() { return this.baos.toByteArray(); } @Override public void setWriteListener(WriteListener listener) { } }
同样的思路,我们在过滤器里面对响应结果进行加密。
/** * Created by jianggc at 2022/4/5. */ @WebFilter(urlPatterns={"/*"}) public class ResponseAesFilter implements Filter { private static final Logger logger= LoggerFactory.getLogger(ResponseAesFilter.class); @Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response); HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest; String requestURI = httpServletRequest.getRequestURI(); chain.doFilter(servletRequest, responseWrapper); String wrapperContent = responseWrapper.getContent(); logger.debug("当前请求requestURI:{}",requestURI); logger.debug("当前请求获取的响应数据:{}",wrapperContent); if(requestURI.startsWith("/app")){// 只对安卓端进行处理 try{ JSONObject parseObject = JSONObject.parseObject(wrapperContent); JSONObject dataObj = parseObject.getJSONObject("data"); if(dataObj!=null&&!dataObj.isEmpty()){ String dataObjStr=JsonUtil.replaceAllBlank(dataObj.toJSONString()); String encryptBase64 = AesUtils.encryptBase64(dataObjStr, AesUtils.aesKey); logger.debug("加密后的响应data:{}",encryptBase64); parseObject.put("data",JsonUtil.replaceAllBlank(encryptBase64)); String decryptBase64 = AesUtils.decryptBase64(encryptBase64, AesUtils.aesKey); logger.debug("解密后的响应data:{}",decryptBase64); } wrapperContent=parseObject.toJSONString(); logger.debug("当前安卓请求加密的响应数据:{}",wrapperContent); }catch (Exception e){ logger.error(e.getMessage(),e); } } ServletOutputStream out = response.getOutputStream(); out.write(wrapperContent.getBytes(Charset.forName("UTF-8"))); out.flush(); } }
【3】JSON流替换request
【1】中有一个弊端就是不能处理json,request.getParameterMap()只能处理form-data(queryString)数据,没有办法处理application/json的数据。所以我们采用如下格式来兼容:
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper{ private static final Logger logger= LoggerFactory.getLogger(BodyReaderHttpServletRequestWrapper.class); private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); body = getBodyString(request).getBytes(Charset.forName("UTF-8")); } private static String getBodyString(ServletRequest request) { StringBuilder sb = new StringBuilder(); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = request.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { logger.error(e.getMessage(),e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.error(e.getMessage(),e); } } if (reader != null) { try { reader.close(); } catch (IOException e) { logger.error(e.getMessage(),e); } } } return sb.toString(); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } public boolean isFinished() { return false; } public boolean isReady() { return false; } public void setReadListener(ReadListener arg0) { // TODO Auto-generated method stub } }; } }
可以看到这里我们缓存body字节流来实现request重复读取流。需要特别注意的是,当你替换request的时候,不要对上传文件请求进行处理否则就会抛出类似下面异常。
Caused by: org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.handleParseFailure(StandardMultipartHttpServletRequest.java:124) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:115) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:87) at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1178) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1012) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ... 48 common frames omitted Caused by: java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed at org.apache.catalina.connector.Request.parseParts(Request.java:2916) at org.apache.catalina.connector.Request.getParts(Request.java:2771) at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) at javax.servlet.http.HttpServletRequestWrapper.getParts(HttpServletRequestWrapper.java:359) at javax.servlet.http.HttpServletRequestWrapper.getParts(HttpServletRequestWrapper.java:359) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ... 54 common frames omitted Caused by: org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:306) at org.apache.catalina.connector.Request.parseParts(Request.java:2869) ... 59 common frames omitted Caused by: java.io.IOException: Stream closed at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:359) at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) at java.io.FilterInputStream.read(FilterInputStream.java:133) at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:132) at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:977) at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:881) at java.io.InputStream.read(InputStream.java:101) at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) at org.apache.tomcat.util.http.fileupload.MultipartStream.readBodyData(MultipartStream.java:572) at org.apache.tomcat.util.http.fileupload.MultipartStream.discardBodyData(MultipartStream.java:596) at org.apache.tomcat.util.http.fileupload.MultipartStream.skipPreamble(MultipartStream.java:614) at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.findNextItem(FileItemIteratorImpl.java:213) at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.<init>(FileItemIteratorImpl.java:127) at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) ... 60 common frames omitted