Skip to content

Quick way to secure web application on Tomcat 6 using BASIC authentication

Updated: at 02:43 PM

You are developing a Java web application, the final application will use some complex security framework (such as Spring Security, formerly Acegi, JSecurity or Shiro, etc.). But in some first milestones, the clients want you to show them the demo of the application, and they want to secure the demo site with a username/password (for things like NDA) and they don’t want to wait for later milestones to have that. In this situation, you cannot integrate the above security frameworks because of time constraint, bugs or the complexity of the security frameworks.

A quick and dirty way to do this is using a built-in authentication mechanism of Tomcat (I’m using Tomcat 6.x).

First put those into your web.xml file:

<web-app>

<security-constraint>
 <web-resource-collection>
  <web-resource-name>EntireApp</web-resource-name>
  <url-pattern>/*</url-pattern>
  <http-method>GET</http-method>
  <http-method>POST</http-method>
 </web-resource-collection>
 <auth-constraint>
  <role-name>client</role-name>
 </auth-constraint></security-constraint>

<security-role>
  <role-name>client</role-name>
</security-role>

<login-config>
 <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

If you use Spring Security, remember to remove Spring Security filter in the web.xml file. Now in your context file (the context.xml file in your META-INF of your web archive or in ther conf/Catalina/localhost/ context file), adding the following:

<context>
  <realm classname="org.apache.catalina.realm.UserDatabaseRealm" resourcename="UserDatabase"></realm>
  <resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" readonly="true" type="org.apache.catalina.UserDatabase">
  </resource>
</context>

Finally, edit the tomcat-users.xml (usually located at <tomcat_install_path>/conf/tomcat-users.xml) to include all the roles you’ve specified in the security constraint of you web application, my tomcat-users.xml looks like this (yours may be different):

<tomcat-users>
    <role rolename="client"></role>
    <user password="client_password" roles="client" username="client_username"></user>
</tomcat-users>

Now, every time the clients access the demo site, the browser will pop up a dialog asking for username and password. After successfully authenticated, the clients will use the demo site as normal.

This authentication mechanism is the Basic access authentication. As the title said, this is a quick and dirty way to secure a web application on Tomcat 6.

Hope this saves you some time.