Jhays
Jhays

Reputation: 23

Filter only post method request with a specific parameter name

How do I filter requests with a specific parameter: e.g. filter only request with "csrf-token" parameter name. The filter will first check if the request has the required parameter name and bypass those without the required parameter.

Below is how I setup my web.xml file but the problem is that all requests are filtered:

<filter>
    <filter-name>CSRFTest</filter-name>
    <filter-class>org.example.CSRFFilter</filter-class>
    <init-param>
        <param-name>csrf_token</param-name>
        <param-value>csrf</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CSRFTest</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>CrossSiteScriptStripper</filter-name>
    <filter-class>CrossSiteScriptStripperFilter</filter-class>
</filter>

<!-- Apply the CrossSiteScriptStripper filter to all servlets and JSP pages. -->
<filter-mapping>
    <filter-name>CrossSiteScriptStripper</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The answers given by pb2q is working on my TEST PROJECT but I'm getting an error when inserted on my real project. I would like to ask if its possible to use 2 filters?

Upvotes: 2

Views: 3315

Answers (1)

pb2q
pb2q

Reputation: 59607

Your Filter class will receive a ServletRequest in its doFilter method: this is analogous to a regular servlet's service method (or doGet, doPost, for HTTPServlet).

In your doFilter method, check the request for the required parameter using ServletRequest.getParameter: if the parameter doesn't exist, the method will return null.

If the parameter doesn't exist then block the request: don't pass it back into the filter chain using FilterChain.doFilter.

Pseudocode:

public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain)
{
    // ...

    if (req.getParameter(MY_PARAMNAME) != null)
        chain.doFilter(req, resp);
    // otherwise don't call doFilter

    // ...
}

I'm not sure what you're expecting to do with the params in your config file, but if you want to specify which HTTP query parameter is required in the request, you might use this config/code combo:

<param-name>required_parameter_name</param-name>
<param-value>csrf-token</param-value>

Then in your init method:

public void init(FilterConfig filterConfig)
{
    // ...

    // use this value in your doFilter method, in place of MY_PARAMNAME, above
    this.requiredParameterName =
        filterConfig.getInitParameter("required_parameter_name");
}

Upvotes: 3

Related Questions