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?
Your
Filterclass will receive aServletRequestin itsdoFiltermethod: this is analogous to a regular servlet’sservicemethod (ordoGet,doPost, forHTTPServlet).In your
doFiltermethod, check the request for the required parameter usingServletRequest.getParameter: if the parameter doesn’t exist, the method will returnnull.If the parameter doesn’t exist then block the request: don’t pass it back into the filter chain using
FilterChain.doFilter.Pseudocode:
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:
Then in your
initmethod: