Question

Thanks to everyone in advance -

How would I go about disabling access via the browser by filetype?

For instance if I wanted to disable all access to .xml files how would I go about doing this?

Thanks

Was it helpful?

Solution

As far as I know there is no straightforward solution for this. At the end of this post, it is explained how you can use JDBCRealm to create a security context around some files of your election. If a user tries to access a file that match your pattern (in your case *.xml), they would be redirected to a login or an error page.

OTHER TIPS

I wanted an answer to this myself, and wasn't satisfied with the JDBCRealm answer.

The default hidden folders "WEB-INF" and "META-INF" are hard coded in the Static Resource logic, so using the same mechanism seems prohibitively difficult. You'd have to replace or modify some combination of DefaultServlet, StandardContext, and StandardContextValve. It's a mess.

But there are two simple ways I tried that accomplish the filtering you're after.

Using a Filter

You can write a generic Servlet Filter to return 404 errors for any file matching some list. You could setup that list as Environment Entries in context.xml, in a properties file on the classpath, stored in a database, or whatever your preference (even as hard-coded Strings, if you're some sort of masochist).

Using a Valve (Tomcat-specific)

Tomcat Valves accomplish pretty much the same thing as Filters, but at a lower level. They are not part of the Servlet Spec, so your app wont be portable to other Servlet Containers. Also, in my experiments with this, sending 404 responses do not go through the same channel as 404 responses sent normally in your application (e.g., if you setup custom 404 pages or handlers, they aren't used when a 404 returns from a Valve)

There is even simpler way. You just redirect all requests with the specific extension to some empty servlet.

Like this:

<servlet-mapping>
   <servlet-name>Empty Servlet</servlet-name>
   <url-pattern>*.xml</url-pattern>
</servlet-mapping>

This does not work with Tomcat that does not accept a servlet-mapping without a corresponding servlet declaration. I would recommend writting a simple ErrorServlet that sends 404 systematically such as:

package com.yourpackage;

public class ErrorServlet extends HttpServlet{
  public ErrorServlet(){
  }
  public void service(HttpServletRequest request, HttpServletResponse response){
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
  }
}

Then add the corresponding configuration in the web.xml file:

<servlet>
  <description>Servlet that displays a 404</description>
  <display-name>error</display-name>
  <servlet-class>com.yourpackage.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>error</servlet-name>
   <url-pattern>*.xhmtl</url-pattern>
</servlet-mapping>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top