How to use htpasswd protection in Tomcat?

Juha Syrjälä picture Juha Syrjälä · Feb 27, 2009 · Viewed 12k times · Source

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?

Answer

Andreas picture Andreas · Feb 8, 2010

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:

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

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