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

查看:135
本文介绍了使用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.

我想编写一个像这样的Filter类:

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天全站免登陆