alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Tomcat example source code file (realm-howto.xml)

This example Tomcat source code file (realm-howto.xml) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Tomcat tags/keywords

digested, if, if, jdbc, jndi, ldap, passwords, realm, realm, the, the, this, tomcat, tomcat

The Tomcat realm-howto.xml source code

<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE document [
  <!ENTITY project SYSTEM "project.xml">
]>
<document url="realm-howto.html">

    &project;

    <properties>
        <author email="craigmcc@apache.org">Craig R. McClanahan
        <author email="yoavs@apache.org">Yoav Shapira
        <author email="arjaquith@mindspring.com">Andrew R. Jaquith
        <title>Realm Configuration HOW-TO
    </properties>

<body>


<section name="Table of Contents">

<p>
<a href="#Quick Start">Quick Start
<blockquote> <a href="#What is a Realm?">What is a Realm?
<a href="#Configuring a Realm">Configuring a Realm
</blockquote> <a href="#Common Features">Common Features
<blockquote> <a href="#Digested Passwords">Digested Passwords
<a href="#Example Application">Example Application
<a href="#Manager Application">Manager Application
<a href="#Realm Logging">Logging Within Realms
</blockquote> <a href="#Standard Realm Implementations"> Standard Realm Implementations</a>
<blockquote> <a href="#JDBCRealm">JDBCRealm
<a href="#DataSourceRealm">DataSourceRealm
<a href="#JNDIRealm">JNDIRealm
<a href="#MemoryRealm">MemoryRealm
<a href="#JAASRealm">JAASRealm
</blockquote> </p> </section> <section name="Quick Start"> <p>This document describes how to configure Tomcat to support container managed security</em>, by connecting to an existing "database" of usernames, passwords, and user roles. You only need to care about this if you are using a web application that includes one or more <code><security-constraint> elements, and a <code><login-config> element defining how users are required to authenticate themselves. If you are not utilizing these features, you can safely skip this document.</p> <p>For fundamental background information about container managed security, see the <a href="http://java.sun.com/products/servlet/download.html">Servlet Specification (Version 2.4)</a>, Section 12.

<p>For information about utilizing the Single Sign On feature of Tomcat 6 (allowing a user to authenticate themselves once across the entire set of web applications associated with a virtual host), see <a href="config/host.html#Single Sign On">here.

</section> <section name="Overview"> <subsection name="What is a Realm?"> <p>A Realm is a "database" of usernames and passwords that identify valid users of a web application (or set of web applications), plus an enumeration of the list of <em>roles
associated with each valid user. You can think of roles as similar to <em>groups in Unix-like operating systems, because access to specific web application resources is granted to all users possessing a particular role (rather than enumerating the list of associated usernames). A particular user can have any number of roles associated with their username.</p> <p>Although the Servlet Specification describes a portable mechanism for applications to <em>declare their security requirements (in the <code>web.xml deployment descriptor), there is no portable API defining the interface between a servlet container and the associated user and role information. In many cases, however, it is desireable to "connect" a servlet container to some existing authentication database or mechanism that already exists in the production environment. Therefore, Tomcat 6 defines a Java interface (<code>org.apache.catalina.Realm) that can be implemented by "plug in" components to establish this connection. Five standard plug-ins are provided, supporting connections to various sources of authentication information:</p> <ul> <li>JDBCRealm - Accesses authentication information stored in a relational database, accessed via a JDBC driver.</li> <li>DataSourceRealm - Accesses authentication information stored in a relational database, accessed via a named JNDI JDBC DataSource.</li> <li>JNDIRealm - Accesses authentication information stored in an LDAP based directory server, accessed via a JNDI provider. </li> <li>MemoryRealm - Accesses authentication information stored in an in-memory object collection, which is initialized from an XML document (<code>conf/tomcat-users.xml). <li>JAASRealm - Accesses authentication information through the Java Authentication & Authorization Service (JAAS) framework.</li> </ul> <p>It is also possible to write your own Realm implementation, and integrate it with Tomcat 6. To do so, you need to: <ul> <li>Implement org.apache.catalina.Realm, <li>Place your compiled realm in $CATALINA_HOME/server/lib, <li>Declare your realm as described in the "Configuring a Realm" section below, <li>Declare your realm to the MBeans Descriptor. </ul> </p> </subsection> <subsection name="Configuring a Realm"> <p>Before getting into the details of the standard Realm implementations, it is important to understand, in general terms, how a Realm is configured. In general, you will be adding an XML element to your <code>conf/server.xml configuration file, that looks something like this:</p> <source> <Realm className="... class name for this implementation" ... other attributes for this implementation .../> </source> <p>The <Realm> element can be nested inside any one of of the following <code>Container elements. The location of the Realm element has a direct impact on the "scope" of that Realm (i.e. which web applications will share the same authentication information): </p> <ul> <li>Inside an <Engine> element - This Realm will be shared across ALL web applications on ALL virtual hosts, UNLESS it is overridden by a Realm element nested inside a subordinate <code><Host> or <code><Context> element. <li>Inside a <Host> element - This Realm will be shared across ALL web applications for THIS virtual host, UNLESS it is overridden by a Realm element nested inside a subordinate <code><Context> element.</li> <li>Inside a <Context> element - This Realm will be used ONLY for THIS web application.</li> </ul> </subsection> </section> <section name="Common Features"> <subsection name="Digested Passwords"> <p>For each of the standard Realm implementations, the user's password (by default) is stored in clear text. In many environments, this is undesireable because casual observers of the authentication data can collect enough information to log on successfully, and impersonate other users. To avoid this problem, the standard implementations support the concept of <em>digesting user passwords. This allows the stored version of the passwords to be encoded (in a form that is not easily reversible), but that the <code>Realm implementation can still utilize for authentication.</p> <p>When a standard realm authenticates by retrieving the stored password and comparing it with the value presented by the user, you can select digested passwords by specifying the <code>digest attribute on your <code><Realm> element. The value for this attribute must be one of the digest algorithms supported by the <code>java.security.MessageDigest class (SHA, MD2, or MD5). When you select this option, the contents of the password that is stored in the <code>Realm must be the cleartext version of the password, as digested by the specified algorithm.</p> <p>When the authenticate() method of the Realm is called, the (cleartext) password specified by the user is itself digested by the same algorithm, and the result is compared with the value returned by the <code>Realm. An equal match implies that the cleartext version of the original password is the same as the one presented by the user, so that this user should be authorized.</p> <p>To calculate the digested value of a cleartext password, two convenience techniques are supported:</p> <ul> <li>If you are writing an application that needs to calculate digested passwords dynamically, call the static <code>Digest() method of the <code>org.apache.catalina.realm.RealmBase class, passing the cleartext password and the digest algorithm name as arguments. This method will return the digested password.</li> <li>If you want to execute a command line utility to calculate the digested password, simply execute <source> java org.apache.catalina.realm.RealmBase \ -a {algorithm} {cleartext-password} </source> and the digested version of this cleartext password will be returned to standard output.</li> </ul> <p>If using digested passwords with DIGEST authentication, the cleartext used to generate the digest is different. In the examples above <code>{cleartext-password} must be replaced with <code>{username}:{realm}:{cleartext-password}. For example, in a development environment this might take the form <code>testUser:localhost:8080:testPassword.

<p>To use either of the above techniques, the <code>$CATALINA_HOME/lib/catalina.jar and <code>$CATALINA_HOME/bin/tomcat-juli.jar files will need to be on your class path to make the <code>RealmBase class available. </p> <p>Non-ASCII usernames and/or passwords are supported using <source>java org.apache.catalina.realm.RealmBase \ -a {algorithm} -e {encoding} {input} </source> but care is required to ensure that the non-ASCII input is correctly passed to the digester. The digester returns <code>{input}:{digest}. If the input appears corrupted in the return, the digest will be invalid.</p> </subsection> <subsection name="Example Application"> <p>The example application shipped with Tomcat 6 includes an area that is protected by a security constraint, utilizing form-based login. To access it, point your browser at <a href="http://localhost:8080/examples/jsp/security/protected/">http://localhost:8080/examples/jsp/security/protected/ and log on with one of the usernames and passwords described for the default <a href="#MemoryRealm">MemoryRealm.

</subsection> <subsection name="Manager Application"> <p>If you wish to use the Manager Application to deploy and undeploy applications in a running Tomcat 6 installation, you MUST add the "manager" role to at least one username in your selected Realm implementation. This is because the manager web application itself uses a security constraint that requires role "manager" to access ANY request URI within that application.</p> <p>For security reasons, no username in the default Realm (i.e. using <code>conf/tomcat-users.xml is assigned the "manager" role. Therfore, no one will be able to utilize the features of this application until the Tomcat administrator specifically assigns this role to one or more users.</p> </subsection> <subsection name="Realm Logging"> <p>Debugging and exception messages logged by a Realm will be recorded by the logging configuration associated with the container for the realm: its surrounding <a href="config/context.html">Context, <a href="config/host.html">Host, or <a href="config/engine.html">Engine.

</subsection> </section> <section name="Standard Realm Implementations"> <subsection name="JDBCRealm"> <h3>Introduction <p>JDBCRealm is an implementation of the Tomcat 6 <code>Realm interface that looks up users in a relational database accessed via a JDBC driver. There is substantial configuration flexibility that lets you adapt to existing table and column names, as long as your database structure conforms to the following requirements:</p> <ul> <li>There must be a table, referenced below as the users table, that contains one row for every valid user that this <code>Realm should recognize.</li> <li>The users table must contain at least two columns (it may contain more if your existing applications required it): <ul> <li>Username to be recognized by Tomcat when the user logs in. <li>Password to be recognized by Tomcat when the user logs in. This value may in cleartext or digested - see below for more information.</li> </ul> <li>There must be a table, referenced below as the user roles table, that contains one row for every valid role that is assigned to a particular user. It is legal for a user to have zero, one, or more than one valid role.</li> <li>The user roles table must contain at least two columns (it may contain more if your existing applications required it): <ul> <li>Username to be recognized by Tomcat (same value as is specified in the <em>users table). <li>Role name of a valid role associated with this user. </ul> </ul> <h3>Quick Start <p>To set up Tomcat to use JDBCRealm, you will need to follow these steps:

<ol> <li>If you have not yet done so, create tables and columns in your database that conform to the requirements described above.</li> <li>Configure a database username and password for use by Tomcat, that has at least read only access to the tables described above. (Tomcat will never attempt to write to these tables.)</li> <li>Place a copy of the JDBC driver you will be using inside the <code>$CATALINA_HOME/lib directory. Note that <strong>only JAR files are recognized! <li>Set up a <Realm> element, as described below, in your <code>$CATALINA_HOME/conf/server.xml file. <li>Restart Tomcat 6 if it is already running. </ol> <h3>Realm Element Attributes <p>To configure JDBCRealm, you will create a <Realm> element and nest it in your <code>$CATALINA_HOME/conf/server.xml file, as described <a href="#Configuring a Realm">above. The following attributes are supported by this implementation:</p> <attributes> <attribute name="className" required="true"> <p>The fully qualified Java class name of this Realm implementation. You <strong>MUST specify the value "<code>org.apache.catalina.realm.JDBCRealm" here.

</attribute> <attribute name="connectionName" required="true"> <p>The database username used to establish a JDBC connection.

</attribute> <attribute name="connectionPassword" required="true"> <p>The database password used to establish a JDBC connection.

</attribute> <attribute name="connectionURL" required="true"> <p>The database URL used to establish a JDBC connection.

</attribute> <attribute name="digest" required="false"> <p>The digest algorithm used to store passwords in non-plaintext formats. Valid values are those accepted for the algorithm name by the <code>java.security.MessageDigest class. See <a href="#Digested Passwords">Digested Passwords for more information. If not specified, passwords are stored in clear text.</p> </attribute> <attribute name="driverName" required="true"> <p>The fully qualified Java class name of the JDBC driver to be used. Consult the documentation for your JDBC driver for the appropriate value.</p> </attribute> <attribute name="roleNameCol" required="true"> <p>The name of the column, in the user roles table, that contains the name of a role assigned to this user.</p> </attribute> <attribute name="userCredCol" required="true"> <p>The name of the column, in the users table, that contains the password for this user (either in clear text, or digested if the <code>digest attribute is set).

</attribute> <attribute name="userNameCol" required="true"> <p>The name of the column, in the users and user roles tables, that contains the username of this user.</p> </attribute> <attribute name="userRoleTable" required="true"> <p>The name of the table that contains one row for each role assigned to a particular <em>username. This table must include at least the columns named by the <code>userNameCol and <code>roleNameCol attributes.

</attribute> <attribute name="userTable" required="true"> <p>The name of the table that contains one row for each username to be recognized by Tomcat. This table must include at least the columns named by the <code>userNameCol and userCredCol attributes.</p> </attribute> </attributes> <h3>Example <p>An example SQL script to create the needed tables might look something like this (adapt the syntax as required for your particular database):</p> <source> create table users ( user_name varchar(15) not null primary key, user_pass varchar(15) not null ); create table user_roles ( user_name varchar(15) not null, role_name varchar(15) not null, primary key (user_name, role_name) ); </source> <p>Example Realm elements are included (commented out) in the default <code>$CATALINA_HOME/conf/server.xml file. Here's an example for using a MySQL database called "authority", configured with the tables described above, and accessed with username "dbuser" and password "dbpass":</p> <source> <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99" driverName="org.gjt.mm.mysql.Driver" connectionURL="jdbc:mysql://localhost/authority?user=dbuser&amp;password=dbpass" userTable="users" userNameCol="user_name" userCredCol="user_pass" userRoleTable="user_roles" roleNameCol="role_name"/> </source> <h3>Additional Notes <p>JDBCRealm operates according to the following rules:

<ul> <li>When a user attempts to access a protected resource for the first time, Tomcat 6 will call the <code>authenticate() method of this <code>Realm. Thus, any changes you have made to the database directly (new users, changed passwords or roles, etc.) will be immediately reflected.</li> <li>Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser). The cached user is <strong>not saved and restored across sessions serialisations. Any changes to the database information for an already authenticated user will <strong>not be reflected until the next time that user logs on again.</li> <li>Administering the information in the users and user roles table is the responsibility of your own applications. Tomcat does not provide any built-in capabilities to maintain users and roles.</li> </ul> </subsection> <subsection name="DataSourceRealm"> <h3>Introduction <p>DataSourceRealm is an implementation of the Tomcat 6 <code>Realm interface that looks up users in a relational database accessed via a JNDI named JDBC DataSource. There is substantial configuration flexibility that lets you adapt to existing table and column names, as long as your database structure conforms to the following requirements:</p> <ul> <li>There must be a table, referenced below as the users table, that contains one row for every valid user that this <code>Realm should recognize.</li> <li>The users table must contain at least two columns (it may contain more if your existing applications required it): <ul> <li>Username to be recognized by Tomcat when the user logs in. <li>Password to be recognized by Tomcat when the user logs in. This value may in cleartext or digested - see below for more information.</li> </ul> <li>There must be a table, referenced below as the user roles table, that contains one row for every valid role that is assigned to a particular user. It is legal for a user to have zero, one, or more than one valid role.</li> <li>The user roles table must contain at least two columns (it may contain more if your existing applications required it): <ul> <li>Username to be recognized by Tomcat (same value as is specified in the <em>users table). <li>Role name of a valid role associated with this user. </ul> </ul> <h3>Quick Start <p>To set up Tomcat to use DataSourceRealm, you will need to follow these steps:

<ol> <li>If you have not yet done so, create tables and columns in your database that conform to the requirements described above.</li> <li>Configure a database username and password for use by Tomcat, that has at least read only access to the tables described above. (Tomcat will never attempt to write to these tables.)</li> <li>Configure a JNDI named JDBC DataSource for your database. Refer to the <a href="jndi-datasource-examples-howto.html">JNDI DataSource Example HOW-TO for information on how to configure a JNDI named JDBC DataSource.</li> <li>Set up a <Realm> element, as described below, in your <code>$CATALINA_HOME/conf/server.xml file. <li>Restart Tomcat 6 if it is already running. </ol> <h3>Realm Element Attributes <p>To configure DataSourceRealm, you will create a <Realm> element and nest it in your <code>$CATALINA_HOME/conf/server.xml file, as described <a href="#Configuring a Realm">above. The following attributes are supported by this implementation:</p> <attributes> <attribute name="className" required="true"> <p>The fully qualified Java class name of this Realm implementation. You <strong>MUST specify the value "<code>org.apache.catalina.realm.DataSourceRealm" here.

</attribute> <attribute name="dataSourceName" required="true"> <p>The JNDI named JDBC DataSource for your database. If the DataSource is local to the context, the name is relative to <code>java:/comp/env, and otherwise the name should match the name used to define the global DataSource.</p> </attribute> <attribute name="digest" required="false"> <p>The digest algorithm used to store passwords in non-plaintext formats. Valid values are those accepted for the algorithm name by the <code>java.security.MessageDigest class. See <a href="#Digested Passwords">Digested Passwords for more information. If not specified, passwords are stored in clear text.</p> </attribute> <attribute name="localDataSource" required="false"> <p>When the realm is nested inside a Context element, this allows the realm to use a DataSource defined for the Context rather than a global DataSource. If not specified, the default is <code>false: use a global DataSource.</p> </attribute> <attribute name="roleNameCol" required="true"> <p>The name of the column, in the user roles table, that contains the name of a role assigned to this user.</p> </attribute> <attribute name="userCredCol" required="true"> <p>The name of the column, in the users table, that contains the password for this user (either in clear text, or digested if the <code>digest attribute is set).

</attribute> <attribute name="userNameCol" required="true"> <p>The name of the column, in the users and user roles tables, that contains the username of this user.</p> </attribute> <attribute name="userRoleTable" required="true"> <p>The name of the table that contains one row for each role assigned to a particular <em>username. This table must include at least the columns named by the <code>userNameCol and <code>roleNameCol attributes.

</attribute> <attribute name="userTable" required="true"> <p>The name of the table that contains one row for each username to be recognized by Tomcat. This table must include at least the columns named by the <code>userNameCol and userCredCol attributes.</p> </attribute> </attributes> <h3>Example <p>An example SQL script to create the needed tables might look something like this (adapt the syntax as required for your particular database):</p> <source> create table users ( user_name varchar(15) not null primary key, user_pass varchar(15) not null ); create table user_roles ( user_name varchar(15) not null, role_name varchar(15) not null, primary key (user_name, role_name) ); </source> <p>Here is an example for using a MySQL database called "authority", configured with the tables described above, and accessed with the JNDI JDBC DataSource with name "java:/comp/env/jdbc/authority".</p> <source> <Realm className="org.apache.catalina.realm.DataSourceRealm" debug="99" dataSourceName="jdbc/authority" userTable="users" userNameCol="user_name" userCredCol="user_pass" userRoleTable="user_roles" roleNameCol="role_name"/> </source> <h3>Additional Notes <p>DataSourceRealm operates according to the following rules:

<ul> <li>When a user attempts to access a protected resource for the first time, Tomcat 6 will call the <code>authenticate() method of this <code>Realm. Thus, any changes you have made to the database directly (new users, changed passwords or roles, etc.) will be immediately reflected.</li> <li>Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser). The cached user is <strong>not saved and restored across sessions serialisations. Any changes to the database information for an already authenticated user will <strong>not be reflected until the next time that user logs on again.</li> <li>Administering the information in the users and user roles table is the responsibility of your own applications. Tomcat does not provide any built-in capabilities to maintain users and roles.</li> </ul> </subsection> <subsection name="JNDIRealm"> <h3>Introduction <p>JNDIRealm is an implementation of the Tomcat 6 <code>Realm interface that looks up users in an LDAP directory server accessed by a JNDI provider (typically, the standard LDAP provider that is available with the JNDI API classes). The realm supports a variety of approaches to using a directory for authentication.</p> <h4>Connecting to the directory <p>The realm's connection to the directory is defined by the <strong>connectionURL configuration attribute. This is a URL whose format is defined by the JNDI provider. It is usually an LDAP URL that specifies the domain name of the directory server to connect to, and optionally the port number and distinguished name (DN) of the required root naming context.</p> <p>If you have more than one provider you can configure an <strong>alternateURL. If a socket connection can not be made to the provider at the <strong>connectionURL an attempt will be made to use the <strong>alternateURL.

<p>When making a connection in order to search the directory and retrieve user and role information, the realm authenticates itself to the directory with the username and password specified by the <strong>connectionName and <strong>connectionPassword properties. If these properties are not specified the connection is anonymous. This is sufficient in many cases. </p> <h4>Selecting the user's directory entry <p>Each user that can be authenticated must be represented in the directory by an individual entry that corresponds to an element in the initial <code>DirContext defined by the <strong>connectionURL attribute. This user entry must have an attribute containing the username that is presented for authentication.</p> <p>Often the distinguished name of the user's entry contains the username presented for authentication but is otherwise the same for all users. In this case the <strong>userPattern attribute may be used to specify the DN, with "{0}" marking where the username should be substituted.</p> <p>Otherwise the realm must search the directory to find a unique entry containing the username. The following attributes configure this search: <ul> <li>userBase - the entry that is the base of the subtree containing users. If not specified, the search base is the top-level context.</li> <li>userSubtree - the search scope. Set to <code>true if you wish to search the entire subtree rooted at the <strong>userBase entry. The default value of <code>false requests a single-level search including only the top level.</li> <li>userSearch - pattern specifying the LDAP search filter to use after substitution of the username.</li> </ul> </p> <h4>Authenticating the user <ul> <li> <p>Bind mode

<p>By default the realm authenticates a user by binding to the directory with the DN of the entry for that user and the password presented by the user. If this simple bind succeeds the user is considered to be authenticated.</p> <p>For security reasons a directory may store a digest of the user's password rather than the clear text version (see <a href="#Digested Passwords">Digested Passwords</a> for more information). In that case, as part of the simple bind operation the directory automatically computes the correct digest of the plaintext password presented by the user before validating it against the stored value. In bind mode, therefore, the realm is not involved in digest processing. The <strong>digest attribute is not used, and will be ignored if set.</p> </li> <li> <p>Comparison mode

<p>Alternatively, the realm may retrieve the stored password from the directory and compare it explicitly with the value presented by the user. This mode is configured by setting the <strong>userPassword attribute to the name of a directory attribute in the user's entry that contains the password.</p> <p>Comparison mode has some disadvantages. First, the <strong>connectionName and <strong>connectionPassword attributes must be configured to allow the realm to read users' passwords in the directory. For security reasons this is generally undesirable; indeed many directory implementations will not allow even the directory manager to read these passwords. In addition, the realm must handle password digests itself, including variations in the algorithms used and ways of representing password hashes in the directory. However, the realm may sometimes need access to the stored password, for example to support HTTP Digest Access Authentication (RFC 2069). (Note that HTTP digest authentication is different from the storage of password digests in the repository for user information as discussed above). </p> </li> </ul> <h4>Assigning roles to the user <p>The directory realm supports two approaches to the representation of roles in the directory:</p> <ul> <li> <p>Roles as explicit directory entries

<p>Roles may be represented by explicit directory entries. A role entry is usually an LDAP group entry with one attribute containing the name of the role and another whose values are the distinguished names or usernames of the users in that role. The following attributes configure a directory search to find the names of roles associated with the authenticated user:</p> <ul> <li>roleBase - the base entry for the role search. If not specified, the search base is the top-level directory context.</li> <li>roleSubtree - the search scope. Set to <code>true if you wish to search the entire subtree rooted at the <code>roleBase entry. The default value of <code>false requests a single-level search including the top level only.</li> <li>roleSearch - the LDAP search filter for selecting role entries. It optionally includes pattern replacements "{0}" for the distinguished name and/or "{1}" for the username of the authenticated user.</li> <li>roleName - the attribute in a role entry containing the name of that role.</li> </ul> </li> </ul> <ul> <li> <p>Roles as an attribute of the user entry

<p>Role names may also be held as the values of an attribute in the user's directory entry. Use <strong>userRoleName to specify the name of this attribute.</p> </li> </ul> <p>A combination of both approaches to role representation may be used.

<h3>Quick Start <p>To set up Tomcat to use JNDIRealm, you will need to follow these steps:

<ol> <li>Make sure your directory server is configured with a schema that matches the requirements listed above.</li> <li>If required, configure a username and password for use by Tomcat, that has read only access to the information described above. (Tomcat will never attempt to modify this information.)</li> <li>Place a copy of the JNDI driver you will be using (typically <code>ldap.jar available with JNDI) inside the <code>$CATALINA_HOME/lib directory. <li>Set up a <Realm> element, as described below, in your <code>$CATALINA_HOME/conf/server.xml file. <li>Restart Tomcat 6 if it is already running. </ol> <h3>Realm Element Attributes <p>To configure JNDIRealm, you will create a <Realm> element and nest it in your <code>$CATALINA_HOME/conf/server.xml file, as described <a href="#Configuring a Realm">above. The following attributes are supported by this implementation:</p> <attributes> <attribute name="className" required="true"> <p>The fully qualified Java class name of this Realm implementation. You <strong>MUST specify the value "<code>org.apache.catalina.realm.JNDIRealm" here.

</attribute> <attribute name="connectionName" required="false"> <p>The directory username to use when establishing a connection to the directory for LDAP search operations. If not specified an anonymous connection is made, which is often sufficient unless you specify the <code>userPassword property.</p> </attribute> <attribute name="connectionPassword" required="false"> <p>The directory password to use when establishing a connection to the directory for LDAP search operations. If not specified an anonymous connection is made, which is often sufficient unless you specify the <code>userPassword property.</p> </attribute> <attribute name="connectionURL" required="true"> <p>The connection URL to be passed to the JNDI driver when establishing a connection to the directory.</p> </attribute> <attribute name="contextFactory" required="false"> <p>The fully qualified Java class name of the JNDI context factory to be used for this connection. By default, the standard JNDI LDAP provider is used (<code>com.sun.jndi.ldap.LdapCtxFactory).

</attribute> <attribute name="digest" required="false"> <p>The digest algorithm to apply to the plaintext password offered by the user before comparing it with the value retrieved from the directory. Valid values are those accepted for the algorithm name by the <code>java.security.MessageDigest class. See for more information. If not specified the plaintext password is assumed to be retrieved. Not required unless <code>userPassword is specified</p> </attribute> <attribute name="roleBase" required="false"> <p>The base directory entry for performing role searches. If not specified, the top level element in the directory context will be used.</p> </attribute> <attribute name="roleName" required="false"> <p>The name of the attribute that contains role names in the directory entries found by a role search. In addition you can use the <code>userRoleName property to specify the name of an attribute, in the user's entry, containing additional role names. If <code>roleName is not specified a role search does not take place, and roles are taken only from the user's entry.</p> </attribute> <attribute name="roleSearch" required="false"> <p>The LDAP filter expression used for performing role searches, following the syntax supported by the <code>java.text.MessageFormat class. Use <code>{0} to substitute the distinguished name (DN) of the user, and/or <code>{1} to substitute the username. If not specified a role search does not take place and roles are taken only from the attribute in the user's entry specified by the <code>userRoleName property.

</attribute> <attribute name="roleSubtree" required="false"> <p>Set to true if you want to search the entire subtree of the element specified by the <code>roleBase property for role entries associated with the user. The default value of <code>false causes only the top level to be searched.</p> </attribute> <attribute name="userBase" required="false"> <p>The base element for user searches performed using the <code>userSearch expression. If not specified, the top level element in the directory context will be used. Not used if you are using the <code>userPattern expression.

</attribute> <attribute name="userPassword" required="false"> <p>Name of the attribute in the user's entry containing the user's password. If you specify this value, JNDIRealm will bind to the directory using the values specified by <code>connectionName and <code>connectionPassword properties, and retrieve the corresponding attribute for comparison to the value specified by the user being authenticated. If the <code>digest attribute is set, the specified digest algorithm is applied to the password offered by the user before comparing it with the value retrieved from the directory. If you do <strong>not specify this value, JNDIRealm will attempt a simple bind to the directory using the DN of the user's entry and password specified by the user, with a successful bind being interpreted as an authenticated user.</p> </attribute> <attribute name="userPattern" required="false"> <p>A pattern for the distinguished name (DN) of the user's directory entry, following the syntax supported by the <code>java.text.MessageFormat class with <code>{0} marking where the actual username should be inserted. You can use this property instead of <code>userSearch, userSubtree and <code>userBase when the distinguished name contains the username and is otherwise the same for all users.</p> </attribute> <attribute name="userRoleName" required="false"> <p>The name of an attribute in the user's directory entry containing zero or more values for the names of roles assigned to this user. In addition you can use the <code>roleName property to specify the name of an attribute to be retrieved from individual role entries found by searching the directory. If <code>userRoleName is not specified all the roles for a user derive from the role search.</p> </attribute> <attribute name="userSearch" required="false"> <p>The LDAP filter expression to use when searching for a user's directory entry, with <code>{0} marking where the actual username should be inserted. Use this property (along with the <code>userBase and <code>userSubtree properties) instead of <code>userPattern to search the directory for the user's entry.</p> </attribute> <attribute name="userSubtree" required="false"> <p>Set to true if you want to search the entire subtree of the element specified by the <code>userBase property for the user's entry. The default value of <code>false causes only the top level to be searched. Not used if you are using the <code>userPattern expression.</p> </attribute> </attributes> <h3>Example <p>Creation of the appropriate schema in your directory server is beyond the scope of this document, because it is unique to each directory server implementation. In the examples below, we will assume that you are using a distribution of the OpenLDAP directory server (version 2.0.11 or later), which can be downloaded from <a href="http://www.openldap.org">http://www.openldap.org
. Assume that your <code>slapd.conf file contains the following settings (among others):</p> <source> database ldbm suffix dc="mycompany",dc="com" rootdn "cn=Manager,dc=mycompany,dc=com" rootpw secret </source> <p>We will assume for connectionURL that the directory server runs on the same machine as Tomcat. See <a href="http://java.sun.com/products/jndi/docs.html">http://java.sun.com/products/jndi/docs.html</a> for more information about configuring and using the JNDI LDAP provider.</p> <p>Next, assume that this directory server has been populated with elements as shown below (in LDIF format):</p> <source> # Define top-level entry dn: dc=mycompany,dc=com objectClass: dcObject dc:mycompany # Define an entry to contain people # searches for users are based on this entry dn: ou=people,dc=mycompany,dc=com objectClass: organizationalUnit ou: people # Define a user entry for Janet Jones dn: uid=jjones,ou=people,dc=mycompany,dc=com objectClass: inetOrgPerson uid: jjones sn: jones cn: janet jones mail: j.jones@mycompany.com userPassword: janet # Define a user entry for Fred Bloggs dn: uid=fbloggs,ou=people,dc=mycompany,dc=com objectClass: inetOrgPerson uid: fbloggs sn: bloggs cn: fred bloggs mail: f.bloggs@mycompany.com userPassword: fred # Define an entry to contain LDAP groups # searches for roles are based on this entry dn: ou=groups,dc=mycompany,dc=com objectClass: organizationalUnit ou: groups # Define an entry for the "tomcat" role dn: cn=tomcat,ou=groups,dc=mycompany,dc=com objectClass: groupOfUniqueNames cn: tomcat uniqueMember: uid=jjones,ou=people,dc=mycompany,dc=com uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com # Define an entry for the "role1" role dn: cn=role1,ou=groups,dc=mycompany,dc=com objectClass: groupOfUniqueNames cn: role1 uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com </source> <p>An example Realm element for the OpenLDAP directory server configured as described above might look like this, assuming that users use their uid (e.g. jjones) to login to the application and that an anonymous connection is sufficient to search the directory and retrieve role information:</p> <source> <Realm className="org.apache.catalina.realm.JNDIRealm" debug="99" connectionURL="ldap://localhost:389" userPattern="uid={0},ou=people,dc=mycompany,dc=com" roleBase="ou=groups,dc=mycompany,dc=com" roleName="cn" roleSearch="(uniqueMember={0})" /> </source> <p>With this configuration, the realm will determine the user's distinguished name by substituting the username into the <code>userPattern, authenticate by binding to the directory with this DN and the password received from the user, and search the directory to find the user's roles.</p> <p>Now suppose that users are expected to enter their email address rather than their userid when logging in. In this case the realm must search the directory for the user's entry. (A search is also necessary when user entries are held in multiple subtrees corresponding perhaps to different organizational units or company locations).</p> <p>Further, suppose that in addition to the group entries you want to use an attribute of the user's entry to hold roles. Now the entry for Janet Jones might read as follows:</p> <source> dn: uid=jjones,ou=people,dc=mycompany,dc=com objectClass: inetOrgPerson uid: jjones sn: jones cn: janet jones mail: j.jones@mycompany.com memberOf: role2 memberOf: role3 userPassword: janet </source> <p> This realm configuration would satisfy the new requirements:

<source> <Realm className="org.apache.catalina.realm.JNDIRealm" debug="99" connectionURL="ldap://localhost:389" userBase="ou=people,dc=mycompany,dc=com" userSearch="(mail={0})" userRoleName="memberOf" roleBase="ou=groups,dc=mycompany,dc=com" roleName="cn" roleSearch="(uniqueMember={0})" /> </source> <p>Now when Janet Jones logs in as "j.jones@mycompany.com", the realm searches the directory for a unique entry with that value as its mail attribute and attempts to bind to the directory as <code>uid=jjones,ou=people,dc=mycompany,dc=com with the given password. If authentication succeeds, she is assigned three roles: "role2" and "role3", the values of the "memberOf" attribute in her directory entry, and "tomcat", the value of the "cn" attribute in the only group entry of which she is a member.</p> <p>Finally, to authenticate the user by retrieving the password from the directory and making a local comparison in the realm, you might use a realm configuration like this:</p> <source> <Realm className="org.apache.catalina.realm.JNDIRealm" debug="99" connectionName="cn=Manager,dc=mycompany,dc=com" connectionPassword="secret" connectionURL="ldap://localhost:389" userPassword="userPassword" userPattern="uid={0},ou=people,dc=mycompany,dc=com" roleBase="ou=groups,dc=mycompany,dc=com" roleName="cn" roleSearch="(uniqueMember={0})" /> </source> <p>However, as discussed above, the default bind mode for authentication is usually to be preferred.</p> <h3>Additional Notes <p>JNDIRealm operates according to the following rules:

<ul> <li>When a user attempts to access a protected resource for the first time, Tomcat 6 will call the <code>authenticate() method of this <code>Realm. Thus, any changes you have made to the directory (new users, changed passwords or roles, etc.) will be immediately reflected.</li> <li>Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser). The cached user is <strong>not saved and restored across sessions serialisations. Any changes to the directory information for an already authenticated user will <strong>not be reflected until the next time that user logs on again.</li> <li>Administering the information in the directory server is the responsibility of your own applications. Tomcat does not provide any built-in capabilities to maintain users and roles.</li> </ul> </subsection> <subsection name="MemoryRealm"> <h3>Introduction <p>MemoryRealm is a simple demonstration implementation of the Tomcat 6 <code>Realm interface. It is not designed for production use. At startup time, MemoryRealm loads information about all users, and their corresponding roles, from an XML document (by default, this document is loaded from <code>$CATALINA_HOME/conf/tomcat-users.xml). Changes to the data in this file are not recognized until Tomcat is restarted.</p> <h3>Realm Element Attributes <p>To configure MemoryRealm, you will create a <Realm> element and nest it in your <code>$CATALINA_HOME/conf/server.xml file, as described <a href="#Configuring a Realm">above. The following attributes are supported by this implementation:</p> <attributes> <attribute name="className" required="true"> <p>The fully qualified Java class name of this Realm implementation. You <strong>MUST specify the value "<code>org.apache.catalina.realm.MemoryRealm" here.

</attribute> <attribute name="digest" required="false"> <p>The digest algorithm used to store passwords in non-plaintext formats. Valid values are those accepted for the algorithm name by the <code>java.security.MessageDigest class. See <a href="#Digested Passwords">Digested Passwords for more information. If not specified, passwords are stored in clear text.</p> </attribute> <attribute name="pathname" required="false"> <p>Absolute or relative (to $CATALINA_HOME) pathname of the XML document containing our valid usernames, passwords, and roles. See below for more information on the format of this file. If not specified, the value <code>conf/tomcat-users.xml is used.

</attribute> </attributes> <h3>User File Format <p>The users file (by default, conf/tomcat-users.xml must be an XML document, with a root element <code><tomcat-users>. Nested inside the root element will be a <code><user> element for each valid user, consisting of the following attributes:</p> <ul> <li>name - Username this user must log on with. <li>password - Password this user must log on with (in clear text if the <code>digest attribute was not set on the <code><Realm> element, or digested appropriately as described <a href="#Digested Passwords">here otherwise). <li>roles - Comma-delimited list of the role names associated with this user.</li> </ul> <h3>Example <p>The default installation of Tomcat 6 is configured with a MemoryRealm nested inside the <code><Engine> element, so that it applies to all virtual hosts and web applications. The default contents of the <code>conf/tomcat-users.xml file is:

<source> <tomcat-users> <user name="tomcat" password="tomcat" roles="tomcat" /> <user name="role1" password="tomcat" roles="role1" /> <user name="both" password="tomcat" roles="tomcat,role1" /> </tomcat-users> </source> <h3>Additional Notes <p>MemoryRealm operates according to the following rules:

<ul> <li>When Tomcat first starts up, it loads all defined users and their associated information from the users file. Changes to the data in this file will <strong>not be recognized until Tomcat is restarted.</li> <li>When a user attempts to access a protected resource for the first time, Tomcat 6 will call the <code>authenticate() method of this <code>Realm. <li>Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser). The cached user is <strong>not saved and restored across sessions serialisations.</li> <li>Administering the information in the users file is the responsibility of your application. Tomcat does not provide any built-in capabilities to maintain users and roles.</li> </ul> </subsection> <subsection name="JAASRealm"> <h3>Introduction <p>JAASRealm is an implementation of the Tomcat 4 <code>Realm interface that authenticates users through the Java Authentication & Authorization Service (JAAS) framework, a Java package that is available as an optional package in Java 2 SDK 1.3 and is fully integrated as of SDK 1.4 .</p> <p>Using JAASRealm gives the developer the ability to combine practically any conceivable security realm with Tomcat's CMA. </p> <p>JAASRealm is prototype for Tomcat of the proposed JAAS-based J2EE authentication framework for J2EE v1.4, based on the <a href="http://www.jcp.org/en/jsr/detail?id=196">JCP Specification Request 196</a> to enhance container-managed security and promote 'pluggable' authentication mechanisms whose implementations would be container-independent. </p> <p>Based on the JAAS login module and principal (see javax.security.auth.spi.LoginModule and <code>javax.security.Principal), you can develop your own security mechanism or wrap another third-party mechanism for integration with the CMA as implemented by Tomcat. </p> <h3>Quick Start <p>To set up Tomcat to use JAASRealm with your own JAAS login module, you will need to follow these steps:</p> <ol> <li>Write your own LoginModule, User and Role classes based on JAAS (see <a href="http://java.sun.com/j2se/1.4.1/docs/guide/security/jaas/tutorials/GeneralAcnOnly.html">the JAAS Authentication Tutorial</a> and <a href="http://java.sun.com/j2se/1.4.1/docs/guide/security/jaas/JAASLMDevGuide.html">the JAAS Login Module Developer's Guide</a>) to be managed by the JAAS Login Context (<code>javax.security.auth.login.LoginContext) When developing your LoginModule, note that JAASRealm's built-in <code>CallbackHandler +only recognizes the <code>NameCallback and PasswordCallback at present. </li> <li>Although not specified in JAAS, you should create seperate classes to distinguish between users and roles, extending <code>javax.security.Principal, so that Tomcat can tell which Principals returned from your login module are users and which are roles (see <code>org.apache.catalina.realm.JAASRealm). Regardless, the first Principal returned is <em>always treated as the user Principal. </li> <li>Place the compiled classes on Tomcat's classpath </li> <li>Set up a login.config file for Java (see <li>Configure your security-constraints in your web.xml for the resources you want to protect</li> <li>Configure the JAASRealm module in your server.xml <li>Restart Tomcat 6 if it is already running. </ol> <h3>Realm Element Attributes <p>To configure JAASRealm as for step 6 above, you create a <code><Realm> element and nest it in your <code>$CATALINA_HOME/conf/server.xml file within your <code><Engine> node. The following attributes are supported by this implementation:</p> <attributes> <attribute name="className" required="true"> <p>The fully qualified Java class name of this Realm implementation. You <strong>MUST specify the value "<code>org.apache.catalina.realm.JAASRealm" here.

</attribute> <attribute name="appName" required="true"> <p>The name of the application as configured in your login configuration file (<a href="http://java.sun.com/j2se/1.4.1/docs/guide/security/jaas/tutorials/LoginConfigFile.html">JAAS LoginConfig
).

</attribute> <attribute name="userClassNames" required="true"> <p>A comma-seperated list of the names of the classes that you have made for your user <code>Principals.

</attribute> <attribute name="roleClassNames" required="false"> <p>A comma-seperated list of the names of the classes that you have made for your role <code>Principals.

</attribute> <attribute name="useContextClassLoader" required="false"> <p>Instructs JAASRealm to use the context class loader for loading the user-specified <code>LoginModule class and associated Principal classes. The default value is <code>true, which is backwards-compatible with the way Tomcat 4 works. To load classes using the container's classloader, specify <code>false.

</attribute> </attributes> <h3>Example <p>Here is an example of how your server.xml snippet should look.

<source> <Realm className="org.apache.catalina.realm.JAASRealm" appName="MyFooRealm" userClassNames="org.foobar.realm.FooUser" roleClassNames="org.foobar.realm.FooRole" debug="99"/> </source> <p>It is the responsibility of your login module to create and save User and Role objects representing Principals for the user (<code>javax.security.auth.Subject). If your login module doesn't create a user object but also doesn't throw a login exception, then the Tomcat CMA will break and you will be left at the http://localhost:8080/myapp/j_security_check URI or at some other unspecified location.</p> <p>The flexibility of the JAAS approach is two-fold:

<ul> <li>you can carry out whatever processing you require behind the scenes in your own login module.</li> <li>you can plug in a completely different LoginModule by changing the configuration and restarting the server, without any code changes to your application.</li> </ul> <h3>Additional Notes <ul> <li>When a user attempts to access a protected resource for the first time, Tomcat 6 will call the <code>authenticate() method of this <code>Realm. Thus, any changes you have made in the security mechanism directly (new users, changed passwords or roles, etc.) will be immediately reflected.</li> <li>Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser. Any changes to the security information for an already authenticated user will <strong>not be reflected until the next time that user logs on again.</li> <li>As with other Realm implementations, digested passwords are supported if the <code><Realm> element in server.xml contains a <code>digest attribute; JAASRealm's CallbackHandler will digest the password prior to passing it back to the <code>LoginModule </ul> </subsection> </section> </body> </document>

Other Tomcat examples (source code examples)

Here is a short list of links related to this Tomcat realm-howto.xml source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.