Sunday, December 19, 2010

Configure Tomcat to accept HTTP PUT command

Tomcat by default is not enabled for HTTP PUT command. But, it can be easily configure to support it.

First, in order to allow Tomcat to accept commands other than HTTP GET and PUT we should add to Tomcat’s web.xml the following init param:

<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Note, that Tomcat’s web.xml is usually located under TOMCAT_HOME/conf/web.xml

We would probably want to allow only specific users to access the PUT command, since it is a command that allows putting resources on our server. Therefore, we will add a user to the file: tomcat-users.xml:

<?xml version='1.0' encoding='cp1252'?>
<tomcat-users>
<user name="admin" password="admin" roles="admin" />
</tomcat-users>

Note, that Tomcat’s tomcat-users.xml is usually located under TOMCAT_HOME/conf/tomcat-users.xml

Finally, we should add a security constraint to the web.xml of the specific web application, for which we want to allow PUT command:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<security-constraint>
<web-resource-collection>
<web-resource-name>Demo App</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Demo App</realm-name>
</login-config>
<security-role>
<description>Role for restricted resources</description>
<role-name>admin</role-name>
</security-role>
</web-app>

Note for the following things:

  • The web.xml of your web application is usually located under: TOMCAT_HOME/webapps/YOUR_WEBAPP/WEB-INF/web.xml
  • In order to use the PUT command, you should pass username and password as part of the request (admin/admin in our example).
  • Note that we enable PUT command for the whole web application, but it is also possible to allow the PUT command only to a part of our web application, by using the “url-pattern” option.

3 comments:

  1. hello, i'm java developer in south korea
    i could know Tomcat configuration in this blog

    thanks

    ReplyDelete
  2. it's very helpful and very neat. Thank you so much.

    ReplyDelete
  3. I could enable PUT method for my sample application !
    vielen dank !

    ReplyDelete