Tomcat – How to use htpasswd protection in Tomcat


I have already created a user database file using Apache's htpasswd command. This file is now used by several other application like apache and subversion.

Users in are created like this:

htpasswd /path/to/users.htpasswd peter

This user file is global, not per directory.

How I can make Tomcat 6 use this same file as a security realm?

Best Solution

Most similar to the htpasswd may be the MemoryRealm. I had problems myself to find a simple example how to use it, so I'll post an easy example code here:

  1. Set up a role, username and password in tomcat-users.xml

  2. Your web.xml should contain something like:

            My Protected WebSite 
          <url-pattern> /* </url-pattern>
          <http-method> GET </http-method>
          <http-method> POST </http-method>
        <!-- the same like in your tomcat-users.conf file -->
          <role-name> test </role-name>
        <auth-method> BASIC </auth-method>
        <realm-name>  Basic Authentication </realm-name>
        <description> Test role </description>
        <role-name> test </role-name>
  3. Add this to your server.xml file:

    <Realm className="org.apache.catalina.realm.MemoryRealm"></Realm>