Springboot之登录模块探索(含Token,验证码,网络安全等知识)(7)
2023-05-02 来源:飞速影视
乍一看,是不是没发现哪里预防了XSS,其实正在的关键点在22行和33行代码,里面的SystemHttpServletRequestWrapper类才是关键,这个类是包装类,是替换参数里的ServletRequest类的,为的就是重写里面的方法,来达到预防XSS的目的,因为Spring也是根据ServletRequest类来进行前端参数读取的,所以它就是后端获得数据的源头
1/** 2 * @auther: NiceBin 3 * @description: 包装的httpServlet,进行以下增强 4 * 1.将流数据取出保存,方便多次读出 5 * 2.防止XSS攻击,修改读取数据的方法,过滤敏感字符 6 * @date: 2020/4/23 19:50 7*/ 8publicclass SystemHttpServletRequestWrapper extends HttpServletRequestWrapper { 9privatefinalbyte[] body;10private HttpServletRequest request;1112public SystemHttpServletRequestWrapper(HttpServletRequest request) throws IOException {13super(request);14//打印属性15//printRequestAll(request);16 body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8")); //HttpHelper是我自己写的工具类17this.request = request;18 }1920 @Override21public BufferedReader getReader() throws IOException {22returnnew BufferedReader(new InputStreamReader(getInputStream()));23 }2425 @Override26public ServletInputStream getInputStream() throws IOException {27final ByteArrayInputStream bais = new ByteArrayInputStream(body);28returnnew ServletInputStream() {29 @Override30publicboolean isFinished() {31returnfalse;32 }3334 @Override35publicboolean isReady() {36returnfalse;37 }3839 @Override40publicvoid setReadListener(ReadListener readListener) {4142 }4344 @Override45publicint read() throws IOException {46return bais.read();47 }48 };49 }5051/**52 * 可以打印出HttpServletRequest里属性的值53 * @param request54*/55publicvoid printRequestAll(HttpServletRequest request){56 Enumeration e = request.getHeaderNames();57while (e.hasMoreElements()) {58 String name = (String) e.nextElement();59 String value = request.getHeader(name);60 System.out.println(name " = " value);61 }62 }6364//以下为XSS预防65 @Override66public String getParameter(String name) {67 String value = request.getParameter(name);68if (!StringUtils.isEmpty(value)) {69 value = StringEscapeUtils.escapeHtml4(value);70 }71return value;72 }7374 @Override75public String[] getParameterValues(String name) {76 String[] parameterValues = super.getParameterValues(name);77if (parameterValues == null) {78returnnull;79 }80for (int i = 0; i < parameterValues.length; i ) {81 String value = parameterValues[i];82 parameterValues[i] = StringEscapeUtils.escapeHtml4(value);83 }84return parameterValues;85 }86 }
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)
www.fs94.org-飞速影视 粤ICP备74369512号