使用 servlet 过滤器修改请求参数 [英] Modify request parameter with servlet filter

查看:22
本文介绍了使用 servlet 过滤器修改请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现有的 Web 应用程序正在 Tomcat 4.1 上运行.页面存在 XSS 问题,但我无法修改源.我决定编写一个 servlet 过滤器来在页面看到参数之前对其进行清理.

An existing web application is running on Tomcat 4.1. There is an XSS issue with a page, but I can't modify the source. I've decided to write a servlet filter to sanitize the parameter before it is seen by the page.

我想写一个像这样的过滤器类:

I would like to write a Filter class like this:

import java.io.*;
import javax.servlet.*;

public final class XssFilter implements Filter {

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException
  {
    String badValue = request.getParameter("dangerousParamName");
    String goodValue = sanitize(badValue);
    request.setParameter("dangerousParamName", goodValue);
    chain.doFilter(request, response);
  }

  public void destroy() {
  }

  public void init(FilterConfig filterConfig) {
  }
}

但是 ServletRequest.setParameter 不存在.

如何在将请求向下传递之前更改请求参数的值?

How can I change the value of the request parameter before passing the request down the chain?

推荐答案

如您所见,HttpServletRequest 没有 setParameter 方法.这是故意的,因为该类代表来自客户端的请求,而修改参数并不代表该请求.

As you've noted HttpServletRequest does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.

一种解决方案是使用 HttpServletRequestWrapper 类,它允许您将一个请求与另一个请求包装在一起.您可以将其子类化,并覆盖 getParameter 方法以返回您的清理值.然后,您可以将包装好的请求传递给 chain.doFilter 而不是原始请求.

One solution is to use the HttpServletRequestWrapper class, which allows you to wrap one request with another. You can subclass that, and override the getParameter method to return your sanitized value. You can then pass that wrapped request to chain.doFilter instead of the original request.

这有点难看,但这就是 servlet API 所说的你应该做的.如果您尝试将其他任何内容传递给 doFilter,一些 servlet 容器会抱怨您违反了规范,并拒绝处理它.

It's a bit ugly, but that's what the servlet API says you should do. If you try to pass anything else to doFilter, some servlet containers will complain that you have violated the spec, and will refuse to handle it.

更优雅的解决方案是更多的工作 - 修改处理参数的原始 servlet/JSP,使其期望请求 属性 而不是参数.过滤器检查参数,对其进行清理,并使用清理后的值设置属性(使用 request.setAttribute).没有子类化,没有欺骗,但确实需要您修改应用程序的其他部分.

A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request attribute instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using request.setAttribute) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.

这篇关于使用 servlet 过滤器修改请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆