Lockoutrealm

Posted : admin On 1/26/2022

Public class LockOutRealm extends CombinedRealm This class extends the CombinedRealm (hence it can wrap other Realms) to provide a user lock out mechanism if there are too many failed authentication attempts in a given period of time. To ensure correct operation, there is a reasonable degree of synchronisation in this Realm. Bna.lockOutRealm.cacheRemovalWarningTime: Indicates the time (in seconds) after which a warning message is logged if a locked user is removed from the cache because the cache is too big before it has been in the cache for at least this period of time. Default value is 3600 (1 hour). To unlock a user.


>
> 04-11 00:00:14 INFO LogRequest > HEAD: https www.defaulthost.com /, FROM: 69.162.124.237, D21FE7FD2B82B776AB194C278244D79E, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.defaulthost.com
> 04-11 00:01:14 INFO LogRequest > HEAD: https www.defaulthost.com /, FROM: 69.162.124.237, D21FE7FD2B82B776AB194C278244D79E, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.defaulthost.com
> 04-11 00:02:14 INFO LogRequest > HEAD: https www.defaulthost.com /, FROM: 69.162.124.237, D21FE7FD2B82B776AB194C278244D79E, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.defaulthost.com
> 04-11 00:03:13 INFO LogRequest > HEAD: https www.defaulthost.com /, FROM: 69.162.124.237, D21FE7FD2B82B776AB194C278244D79E, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.defaulthost.com
>
> 04-11 00:00:32 INFO LogRequest > HEAD: https www.anotherhost.com /, FROM: 69.162.124.237, C62DCA4E9DC39884E3E82EE19AAEAB4A, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.anotherhost.com
> 04-11 00:01:32 INFO LogRequest > HEAD: https www.anotherhost.com /, FROM: 69.162.124.237, 542027513FD08CD82C8BEFF3C4E75F8C, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.anotherhost.com
> 04-11 00:02:32 INFO LogRequest > HEAD: https www.anotherhost.com /, FROM: 69.162.124.237, F93C1929D880DDD446D13E36413544DF, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.anotherhost.com
> 04-11 00:03:32 INFO LogRequest > HEAD: https www.anotherhost.com /, FROM: 69.162.124.237, 82C3BB415817B8C4761EFEF7EE7591DD, Mozilla/5.0+(compatible; UptimeRobot/2.0; http://www.uptimerobot.com/), REFERER: https://www.anotherhost.com
>
> This is with the valve at the engine level, which I assumed meant that it would apply to all hosts within that engine. The documentation states 'Normally, this Valve would be used at the Engine level.', so that's what I did.
>
> https://tomcat.apache.org/tomcat-8.5-doc/config/valve.html#Crawler_Session_Manager_Valve
>
> - Matt
>
> -----Original Message-----
> From: Christopher Schultz <[hidden email]>
> Sent: Wednesday, April 11, 2018 1:46 PM
> To: [hidden email]
> Subject: Re: CrawlerSessionManagerValve only working with default host
>
> Matt,
>
> On 4/11/18 2:03 PM, Matt Cosentino wrote:
>> I have CrawlerSessionManagerValve set up at the Engine level, but it only seems to be working for the default host and not any other host. Is this expected behavior? Should I put it at the host level for each host?
>>
>> Here is an example of how I have it set up:
>>
>> <Engine defaultHost='www.defaulthost.com' name='DefaultHost'>
>> <Realm className='org.apache.catalina.realm.LockOutRealm'>
>> <Realm className='org.apache.catalina.realm.UserDatabaseRealm'/>
>> </Realm>
>> <Host name='www.defaulthost.com' appBase='C:webdefaulthost'/>
>> <Host name='www.anotherhost.com' appBase='C:webanotherhost'/>
>> <Valve className='org.apache.catalina.valves.CrawlerSessionManagerValve' sessionInactiveInterval='300'/>
>> </Engine>
>>
>> Tomcat 8.5.24
>
> I don't see anything in the code that suggests it wouldn't work when used at the <Engine> level, but it also looks like it makes the most sense at the <Context> level.
>
> Can you describe your testing and the results you got?
>
> When you say 'only [...] working for the default host', do you mean that it works for the default host within an <Engine> (when configured at the <Engine> level) or that it doesn't even work with a non-default <Host> when configured at the <Host> level?
>
> -chris
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [hidden email]
> For additional commands, e-mail: [hidden email]
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [hidden email]
> For additional commands, e-mail: [hidden email]
>

Realm Configuration How-To

Table of Contents

  • Overview
  • Common Features
  • Standard Realm Implementations

Quick Start

This document describes how to configure Tomcat to support containermanaged security, by connecting to an existing 'database' of usernames,passwords, and user roles. You only need to care about this if you are usinga web application that includes one or more<security-constraint> elements, and a<login-config> element defining how users are requiredto authenticate themselves. If you are not utilizing these features, you cansafely skip this document.

For fundamental background information about container managed security,see the ServletSpecification (Version 2.4), Section 12.

For information about utilizing the Single Sign On feature ofTomcat (allowing a user to authenticate themselves once across the entireset of web applications associated with a virtual host), seehere.

Overview

What is a Realm?

A Realm is a 'database' of usernames and passwords thatidentify valid users of a web application (or set of web applications), plusan enumeration of the list of roles associated with each valid user.You can think of roles as similar to groups in Unix-like operatingsystems, because access to specific web application resources is granted toall users possessing a particular role (rather than enumerating the list ofassociated usernames). A particular user can have any number of rolesassociated with their username.

Although the Servlet Specification describes a portable mechanism forapplications to declare their security requirements (in theweb.xml deployment descriptor), there is no portable APIdefining the interface between a servlet container and the associated userand role information. In many cases, however, it is desirable to 'connect'a servlet container to some existing authentication database or mechanismthat already exists in the production environment. Therefore, Tomcatdefines a Java interface (org.apache.catalina.Realm) thatcan be implemented by 'plug in' components to establish this connection.Six standard plug-ins are provided, supporting connections to varioussources of authentication information:

  • JDBCRealm - Accesses authentication information stored in a relational database, accessed via a JDBC driver.
  • DataSourceRealm - Accesses authentication information stored in a relational database, accessed via a named JNDI JDBC DataSource.
  • JNDIRealm - Accesses authentication information stored in an LDAP based directory server, accessed via a JNDI provider.
  • UserDatabaseRealm - Accesses authentication information stored in an UserDatabase JNDI resource, which is typically backed by an XML document (conf/tomcat-users.xml).
  • MemoryRealm - Accesses authentication information stored in an in-memory object collection, which is initialized from an XML document (conf/tomcat-users.xml).
  • JAASRealm - Accesses authentication information through the Java Authentication & Authorization Service (JAAS) framework.

It is also possible to write your own Realm implementation,and integrate it with Tomcat. To do so, you need to:

  • Implement org.apache.catalina.Realm,
  • Place your compiled realm in $CATALINA_HOME/lib,
  • Declare your realm as described in the 'Configuring a Realm' section below,
  • Declare your realm to the MBeans Descriptors.

Configuring a Realm

Before getting into the details of the standard Realm implementations, it isimportant to understand, in general terms, how a Realm is configured. Ingeneral, you will be adding an XML element to your conf/server.xmlconfiguration file, that looks something like this:

The <Realm> element can be nested inside any one ofof the following Container elements. The location of theRealm element has a direct impact on the 'scope' of that Realm(i.e. which web applications will share the same authentication information):

  • 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 <Host> or <Context> element.
  • 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 <Context> element.
  • Inside a <Context> element - This Realm will be used ONLY for THIS web application.

Common Features

Digested Passwords

For each of the standard Realm implementations, theuser's password (by default) is stored in clear text. In manyenvironments, this is undesirable because casual observers of theauthentication data can collect enough information to log onsuccessfully, and impersonate other users. To avoid this problem, thestandard implementations support the concept of digestinguser passwords. This allows the stored version of the passwords to beencoded (in a form that is not easily reversible), but that theRealm implementation can still utilize forauthentication.

When a standard realm authenticates by retrieving the storedpassword and comparing it with the value presented by the user, youcan select digested passwords by placing a CredentialHandler element inside your <Realm>element. An easy choice to support one of the algorithms SSHA, SHA or MD5would be the usage of the MessageDigestCredentialHandler.This element must be configured to one of the digest algorithms supportedby the java.security.MessageDigest class (SSHA, SHA or MD5).When you select this option, the contents of the password that is storedin the Realm must be the cleartext version of the password,as digested by the specified algorithm.

When the authenticate() method of the Realm is called, the(cleartext) password specified by the user is itself digested by the samealgorithm, and the result is compared with the value returned by theRealm. An equal match implies that the cleartext version of theoriginal password is the same as the one presented by the user, so that thisuser should be authorized.

To calculate the digested value of a cleartext password, two conveniencetechniques are supported:

  • If you are writing an application that needs to calculate digested passwords dynamically, call the static Digest() method of the org.apache.catalina.realm.RealmBase class, passing the cleartext password, the digest algorithm name and the encoding as arguments. This method will return the digested password.
  • If you want to execute a command line utility to calculate the digested password, simply execute and the digested version of this cleartext password will be returned to standard output.

If using digested passwords with DIGEST authentication, the cleartext used to generate the digest is different and the digest must use one iteration of the MD5 algorithm with no salt. In the examples above {cleartext-password} must be replaced with {username}:{realm}:{cleartext-password}. For example, in a development environment this might take the form testUser:Authentication required:testPassword. The value for {realm} is taken from the <realm-name> element of the web application's <login-config>. If not specified in web.xml, the default value of Authentication required is used.

Usernames and/or passwords using encodings other than the platform defaultare supported using

but care is required to ensure that the input is correctly passed to thedigester. The digester returns {input}:{digest}. If the inputappears corrupted in the return, the digest will be invalid.

The output format of the digest is {salt}${iterations}${digest}.If the salt length is zero and the iteration count is one, the output issimplified to {digest}.

The full syntax of CATALINA_HOME/bin/digest.[bat sh] is:

  • -a - The algorithm to use to generate the stored credential. If not specified, the default for the handler will be used. If neither handler nor algorithm is specified then a default of SHA-512 will be used
  • -e - The encoding to use for any byte to/from character conversion that may be necessary. If not specified, the system encoding (Charset#defaultCharset()) will be used.
  • -i - The number of iterations to use when generating the stored credential. If not specified, the default for the CredentialHandler will be used.
  • -s - The length (in bytes) of salt to generate and store as part of the credential. If not specified, the default for the CredentialHandler will be used.
  • -k - The length (in bits) of the key(s), if any, created while generating the credential. If not specified, the default for the CredentialHandler will be used.
  • -h - The fully qualified class name of the CredentialHandler to use. If not specified, the built-in handlers will be tested in turn (MessageDigestCredentialHandler then SecretKeyCredentialHandler) and the first one to accept the specified algorithm will be used.

Example Application

The example application shipped with Tomcat includes an area that isprotected by a security constraint, utilizing form-based login. To access it,point your browser athttp://localhost:8080/examples/jsp/security/protected/and log on with one of the usernames and passwords described for the defaultUserDatabaseRealm.

Manager Application

If you wish to use the Manager Applicationto deploy and undeploy applications in a running Tomcat installation, youMUST add the 'manager-gui' role to at least one username in your selectedRealm implementation. This is because the manager web application itself uses asecurity constraint that requires role 'manager-gui' to access ANY request URIwithin the HTML interface of that application.

For security reasons, no username in the default Realm (i.e. usingconf/tomcat-users.xml is assigned the 'manager-gui' role.Therefore, no one will be able to utilize the features of this applicationuntil the Tomcat administrator specifically assigns this role to one or moreusers.

Realm Logging

Tomcat

Debugging and exception messages logged by a Realm will be recorded by the logging configuration associated with the container for the realm: its surrounding Context, Host, or Engine.

Standard Realm Implementations

DataSourceRealm

Introduction

DataSourceRealm is an implementation of the TomcatRealm interface that looks up users in a relational databaseaccessed via a JNDI named JDBC DataSource. There is substantial configurationflexibility that lets you adapt to existing table and column names, as longas your database structure conforms to the following requirements:

  • There must be a table, referenced below as the users table, that contains one row for every valid user that this Realm should recognize.
  • The users table must contain at least two columns (it may contain more if your existing applications required it):
    • Username to be recognized by Tomcat when the user logs in.
    • Password to be recognized by Tomcat when the user logs in. This value may in cleartext or digested - see below for more information.
  • 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.
  • The user roles table must contain at least two columns (it may contain more if your existing applications required it):
    • Username to be recognized by Tomcat (same value as is specified in the users table).
    • Role name of a valid role associated with this user.
Quick Start

To set up Tomcat to use DataSourceRealm, you will need to follow these steps:

  1. If you have not yet done so, create tables and columns in your database that conform to the requirements described above.
  2. 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.)
  3. Configure a JNDI named JDBC DataSource for your database. Refer to the JNDI DataSource Example How-To for information on how to configure a JNDI named JDBC DataSource. Be sure to set the Realm's localDataSource attribute appropriately, depending on where the JNDI DataSource is defined.
  4. Set up a <Realm> element, as described below, in your $CATALINA_BASE/conf/server.xml file.
  5. Restart Tomcat if it is already running.
Realm Element Attributes

To configure DataSourceRealm, you will create a <Realm>element and nest it in your $CATALINA_BASE/conf/server.xml file,as described above. The attributes for theDataSourceRealm are defined in the Realmconfiguration documentation.

Example

An example SQL script to create the needed tables might look somethinglike this (adapt the syntax as required for your particular database):

Here is an example for using a MySQL database called 'authority', configuredwith the tables described above, and accessed with the JNDI JDBC DataSource withname 'java:/comp/env/jdbc/authority'.

Additional Notes

DataSourceRealm operates according to the following rules:

  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm. Thus, any changes you have made to the database directly (new users, changed passwords or roles, etc.) will be immediately reflected.
  • 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 not saved and restored across sessions serialisations. Any changes to the database information for an already authenticated user will not be reflected until the next time that user logs on again.
  • 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.

JNDIRealm

Introduction

JNDIRealm is an implementation of the TomcatRealm interface that looks up users in an LDAP directoryserver accessed by a JNDI provider (typically, the standard LDAPprovider that is available with the JNDI API classes). The realmsupports a variety of approaches to using a directory forauthentication.

Connecting to the directory

The realm's connection to the directory is defined by theconnectionURL configuration attribute. This is a URLwhose format is defined by the JNDI provider. It is usually an LDAPURL that specifies the domain name of the directory server to connectto, and optionally the port number and distinguished name (DN) of therequired root naming context.

If you have more than one provider you can configure analternateURL. If a socket connection cannot bemade to the provider at the connectionURL anattempt will be made to use the alternateURL.

When making a connection in order to search the directory andretrieve user and role information, the realm authenticates itself tothe directory with the username and password specified by theconnectionName andconnectionPassword properties. If these propertiesare not specified the connection is anonymous. This is sufficient inmany cases.

Selecting the user's directory entry

Each user that can be authenticated must be represented in thedirectory by an individual entry that corresponds to an element in theinitial DirContext defined by theconnectionURL attribute. This user entry must have anattribute containing the username that is presented forauthentication.

Often the distinguished name of the user's entry contains theusername presented for authentication but is otherwise the same forall users. In this case the userPattern attribute maybe used to specify the DN, with '{0}' marking wherethe username should be substituted.

Otherwise the realm must search the directory to find a unique entrycontaining the username. The following attributes configure thissearch:

  • userBase - the entry that is the base of the subtree containing users. If not specified, the search base is the top-level context.
  • userSubtree - the search scope. Set to true if you wish to search the entire subtree rooted at the userBase entry. The default value of false requests a single-level search including only the top level.
  • userSearch - pattern specifying the LDAP search filter to use after substitution of the username.
Authenticating the user
  • Bind mode

    By default the realm authenticates a user by binding tothe directory with the DN of the entry for that user and the passwordpresented by the user. If this simple bind succeeds the user is considered tobe authenticated.

    For security reasons a directory may store a digest of the user'spassword rather than the clear text version (seeDigested Passwords for more information). In that case,as part of the simple bind operation the directory automaticallycomputes the correct digest of the plaintext password presented by theuser before validating it against the stored value. In bind mode,therefore, the realm is not involved in digest processing. Thedigest attribute is not used, and will be ignored ifset.

  • Comparison mode

    Alternatively, the realm may retrieve the storedpassword from the directory and compare it explicitly with the valuepresented by the user. This mode is configured by setting theuserPassword attribute to the name of a directoryattribute in the user's entry that contains the password.

    Comparison mode has some disadvantages. First, theconnectionName andconnectionPassword attributes must be configured toallow the realm to read users' passwords in the directory. Forsecurity reasons this is generally undesirable; indeed many directoryimplementations will not allow even the directory manager to readthese passwords. In addition, the realm must handle password digestsitself, including variations in the algorithms used and ways ofrepresenting password hashes in the directory. However, the realm maysometimes need access to the stored password, for example to supportHTTP Digest Access Authentication (RFC 2069). (Note that HTTP digestauthentication is different from the storage of password digests inthe repository for user information as discussed above).

Assigning roles to the user

The directory realm supports two approaches to the representationof roles in the directory:

  • Roles as explicit directory entries

    Roles may be represented by explicit directory entries. A roleentry is usually an LDAP group entry with one attributecontaining the name of the role and another whose values are thedistinguished names or usernames of the users in that role. Thefollowing attributes configure a directory search tofind the names of roles associated with the authenticated user:

    • roleBase - the base entry for the role search. If not specified, the search base is the top-level directory context.
    • roleSubtree - the search scope. Set to true if you wish to search the entire subtree rooted at the roleBase entry. The default value of false requests a single-level search including the top level only.
    • 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 and/or '{2}' for an attribute from user's directory entry, of the authenticated user. Use userRoleAttribute to specify the name of the attribute that provides the value for '{2}'.
    • roleName - the attribute in a role entry containing the name of that role.
    • roleNested - enable nested roles. Set to true if you want to nest roles in roles. If configured, then every newly found roleName and distinguished Name will be recursively tried for a new role search. The default value is false.
  • Roles as an attribute of the user entry

    Role names may also be held as the values of an attribute in theuser's directory entry. Use userRoleName to specifythe name of this attribute.

A combination of both approaches to role representation may be used.

Lockoutrealm
Quick Start

To set up Tomcat to use JNDIRealm, you will need to follow these steps:

  1. Make sure your directory server is configured with a schema that matches the requirements listed above.
  2. 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.)
  3. Set up a <Realm> element, as described below, in your $CATALINA_BASE/conf/server.xml file.
  4. Restart Tomcat if it is already running.
Realm Element Attributes

To configure JNDIRealm, you will create a <Realm>element and nest it in your $CATALINA_BASE/conf/server.xml file,as described above. The attributes for theJNDIRealm are defined in the Realm configurationdocumentation.

Example

Creation of the appropriate schema in your directory server is beyond thescope of this document, because it is unique to each directory serverimplementation. In the examples below, we will assume that you are using adistribution of the OpenLDAP directory server (version 2.0.11 or later), whichcan be downloaded fromhttps://www.openldap.org. Assume thatyour slapd.conf file contains the following settings(among others):

We will assume for connectionURL that the directoryserver runs on the same machine as Tomcat. See http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.htmlfor more information about configuring and using the JNDI LDAPprovider.

Next, assume that this directory server has been populated with elementsas shown below (in LDIF format):

An example Realm element for the OpenLDAP directoryserver configured as described above might look like this, assumingthat users use their uid (e.g. jjones) to login to theapplication and that an anonymous connection is sufficient to searchthe directory and retrieve role information:

With this configuration, the realm will determine the user'sdistinguished name by substituting the username into theuserPattern, authenticate by binding to the directorywith this DN and the password received from the user, and search thedirectory to find the user's roles.

Now suppose that users are expected to enter their email addressrather than their userid when logging in. In this case the realm mustsearch the directory for the user's entry. (A search is also necessarywhen user entries are held in multiple subtrees corresponding perhapsto different organizational units or company locations).

Further, suppose that in addition to the group entries you want touse an attribute of the user's entry to hold roles. Now the entry forJanet Jones might read as follows:

This realm configuration would satisfy the new requirements:

Now when Janet Jones logs in as '[email protected]', the realmsearches the directory for a unique entry with that value as its mailattribute and attempts to bind to the directory asuid=jjones,ou=people,dc=mycompany,dc=com with the givenpassword. If authentication succeeds, she is assigned three roles:'role2' and 'role3', the values of the 'memberOf' attribute in herdirectory entry, and 'tomcat', the value of the 'cn' attribute in theonly group entry of which she is a member.

Finally, to authenticate the user by retrievingthe password from the directory and making a local comparison in therealm, you might use a realm configuration like this:

Lockoutrealm

However, as discussed above, the default bind mode forauthentication is usually to be preferred.

Additional Notes

JNDIRealm operates according to the following rules:

  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm. Thus, any changes you have made to the directory (new users, changed passwords or roles, etc.) will be immediately reflected.
  • 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 not saved and restored across sessions serialisations. Any changes to the directory information for an already authenticated user will not be reflected until the next time that user logs on again.
  • 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.

UserDatabaseRealm

Introduction

UserDatabaseRealm is an implementation of the TomcatRealm interface that uses a JNDI resource to store userinformation. By default, the JNDI resource is backed by an XML file. It is notdesigned for large-scale production use. At startup time, the UserDatabaseRealmloads information about all users, and their corresponding roles, from an XMLdocument (by default, this document is loaded from$CATALINA_BASE/conf/tomcat-users.xml). The users, their passwordsand their roles may all be editing dynamically, typically via JMX. Changes maybe saved and will be reflected in the XML file.

Realm Element Attributes

To configure UserDatabaseRealm, you will create a <Realm>element and nest it in your $CATALINA_BASE/conf/server.xml file,as described above. The attributes for theUserDatabaseRealm are defined in the Realmconfiguration documentation.

User File Format

The users file uses the same format as theMemoryRealm.

Example

The default installation of Tomcat is configured with a UserDatabaseRealmnested inside the <Engine> element, so that it appliesto all virtual hosts and web applications. The default contents of theconf/tomcat-users.xml file is:

Additional Notes

UserDatabaseRealm operates according to the following rules:

  • When Tomcat first starts up, it loads all defined users and their associated information from the users file. Changes made to the data in this file will not be recognized until Tomcat is restarted. Changes may be made via the UserDatabase resource. Tomcat provides MBeans that may be accessed via JMX for this purpose.
  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm.
  • 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 not saved and restored across sessions serialisations.

MemoryRealm

Introduction

MemoryRealm is a simple demonstration implementation of theTomcat Realm interface. It is not designed for production use.At startup time, MemoryRealm loads information about all users, and theircorresponding roles, from an XML document (by default, this document is loadedfrom $CATALINA_BASE/conf/tomcat-users.xml). Changes to the datain this file are not recognized until Tomcat is restarted.

Realm Element Attributes

To configure MemoryRealm, you will create a <Realm>element and nest it in your $CATALINA_BASE/conf/server.xml file,as described above. The attributes for theMemoryRealm are defined in the Realmconfiguration documentation.

User File Format

The users file (by default, conf/tomcat-users.xml must be anXML document, with a root element <tomcat-users>. Nestedinside the root element will be a <user> element for eachvalid user, consisting of the following attributes:

  • name - Username this user must log on with.
  • password - Password this user must log on with (in clear text if the digest attribute was not set on the <Realm> element, or digested appropriately as described here otherwise).
  • roles - Comma-delimited list of the role names associated with this user.
Additional Notes

MemoryRealm operates according to the following rules:

  • 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 not be recognized until Tomcat is restarted.
  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm.
  • 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 not saved and restored across sessions serialisations.
  • 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.

JAASRealm

Introduction

JAASRealm is an implementation of the TomcatRealm interface that authenticates users through the JavaAuthentication & Authorization Service (JAAS) framework which is nowprovided as part of the standard Java SE API.

Using JAASRealm gives the developer the ability to combinepractically any conceivable security realm with Tomcat's CMA.

JAASRealm is prototype for Tomcat of the JAAS-basedJ2EE authentication framework for J2EE v1.4, based on the JCP SpecificationRequest 196 to enhance container-managed security and promote'pluggable' authentication mechanisms whose implementations would becontainer-independent.

Based on the JAAS login module and principal (see javax.security.auth.spi.LoginModuleand javax.security.Principal), you can develop your ownsecurity mechanism or wrap another third-party mechanism forintegration with the CMA as implemented by Tomcat.

Quick Start

To set up Tomcat to use JAASRealm with your own JAAS login module, you will need to follow these steps:

  1. Write your own LoginModule, User and Role classes basedon JAAS (seethe JAAS Authentication Tutorial andthe JAAS Login Module Developer's Guide) to be managed by the JAAS LoginContext (javax.security.auth.login.LoginContext)When developing your LoginModule, note that JAASRealm's built-in CallbackHandleronly recognizes the NameCallback and PasswordCallback at present.
  2. Although not specified in JAAS, you should createseparate classes to distinguish between users and roles, extending javax.security.Principal,so that Tomcat can tell which Principals returned from your loginmodule are users and which are roles (see org.apache.catalina.realm.JAASRealm).Regardless, the first Principal returned is always treated as the user Principal.
  3. Place the compiled classes on Tomcat's classpath
  4. Set up a login.config file for Java (see JAAS LoginConfig file) and tell Tomcat where to find it by specifyingits location to the JVM, for instance by setting the environmentvariable: JAVA_OPTS=$JAVA_OPTS -Djava.security.auth.login.config$CATALINA_BASE/conf/jaas.config
  5. Configure your security-constraints in your web.xml forthe resources you want to protect
  6. Configure the JAASRealm module in your server.xml
  7. Restart Tomcat if it is already running.
Realm Element Attributes

To configure JAASRealm as for step 6 above, you createa <Realm> element and nest it in your$CATALINA_BASE/conf/server.xmlfile within your <Engine> node. The attributes for theJAASRealm are defined in the Realmconfiguration documentation.

Example

Here is an example of how your server.xml snippet should look.

It is the responsibility of your login module to create and save User andRole objects representing Principals for the user(javax.security.auth.Subject). If your login module doesn'tcreate a user object but also doesn't throw a login exception, then theTomcat CMA will break and you will be left at thehttp://localhost:8080/myapp/j_security_check URI or at some otherunspecified location.

The flexibility of the JAAS approach is two-fold:

  • you can carry out whatever processing you require behindthe scenes in your own login module.
  • you can plug in a completely different LoginModule by changing the configurationand restarting the server, without any code changes to your application.
Additional Notes
  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm. Thus, any changes you have made in the security mechanism directly (new users, changed passwords or roles, etc.) will be immediately reflected.
  • 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 not be reflected until the next time that user logs on again.
  • As with other Realm implementations, digested passwords are supported if the <Realm> element in server.xml contains a digest attribute; JAASRealm's CallbackHandler will digest the password prior to passing it back to the LoginModule

CombinedRealm

Introduction

CombinedRealm is an implementation of the Tomcat Realm interface that authenticates users through one or more sub-Realms.

Using CombinedRealm gives the developer the ability to combine multiple Realms of the same or different types. This can be used to authenticate against different sources, provide fall back in case one Realm fails or for any other purpose that requires multiple Realms.

Sub-realms are defined by nesting Realm elements inside the Realm element that defines the CombinedRealm. Authentication will be attempted against each Realm in the order they are listed. Authentication against any Realm will be sufficient to authenticate the user.

Realm Element Attributes

To configure a CombinedRealm, you create a <Realm> element and nest it in your $CATALINA_BASE/conf/server.xml file within your <Engine> or <Host>. You can also nest inside a <Context> node in a context.xml file.

Example

Here is an example of how your server.xml snippet should look to use aUserDatabase Realm and a DataSource Realm.

LockOutRealm

Introduction

LockOutRealm is an implementation of the Tomcat Realm interface that extends the CombinedRealm to provide lock out functionality to provide a user lock out mechanism if there are too many failed authentication attempts in a given period of time.

To ensure correct operation, there is a reasonable degree of synchronisation in this Realm.

This Realm does not require modification to the underlying Realms or the associated user storage mechanisms. It achieves this by recording all failed logins, including those for users that do not exist. To prevent a DOS by deliberating making requests with invalid users (and hence causing this cache to grow) the size of the list of users that have failed authentication is limited.

Sub-realms are defined by nesting Realm elements inside the Realm element that defines the LockOutRealm. Authentication will be attempted against each Realm in the order they are listed. Authentication against any Realm will be sufficient to authenticate the user.

Realm Element Attributes

To configure a LockOutRealm, you create a <Realm> element and nest it in your $CATALINA_BASE/conf/server.xml file within your <Engine> or <Host>. You can also nest inside a <Context> node in a context.xml file. The attributes for the LockOutRealm are defined in the Realm configuration documentation.

Example

Here is an example of how your server.xml snippet should look to add lock outfunctionality to a UserDatabase Realm.

JDBCRealm

Introduction

The JDBC Database Realm has been deprecated and will be removedin Tomcat 10 onwards. Use the DataSourceRealm instead.

JDBCRealm is an implementation of the TomcatRealm interface that looks up users in a relational databaseaccessed via a JDBC driver. There is substantial configuration flexibilitythat lets you adapt to existing table and column names, as long as yourdatabase structure conforms to the following requirements:

  • There must be a table, referenced below as the users table, that contains one row for every valid user that this Realm should recognize.
  • The users table must contain at least two columns (it may contain more if your existing applications required it):
    • Username to be recognized by Tomcat when the user logs in.
    • Password to be recognized by Tomcat when the user logs in. This value may in cleartext or digested - see below for more information.
  • 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.
  • The user roles table must contain at least two columns (it may contain more if your existing applications required it):
    • Username to be recognized by Tomcat (same value as is specified in the users table).
    • Role name of a valid role associated with this user.

Lockoutrealm Server.xml

Quick Start

To set up Tomcat to use JDBCRealm, you will need to follow these steps:

  1. If you have not yet done so, create tables and columns in your database that conform to the requirements described above.
  2. 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.)
  3. Place a copy of the JDBC driver you will be using inside the $CATALINA_HOME/lib directory. Note that only JAR files are recognized!
  4. Set up a <Realm> element, as described below, in your $CATALINA_BASE/conf/server.xml file.
  5. Restart Tomcat if it is already running.
Realm Element Attributes

To configure JDBCRealm, you will create a <Realm>element and nest it in your $CATALINA_BASE/conf/server.xml file,as described above. The attributes for theJDBCRealm are defined in the Realm configurationdocumentation.

Lockoutrealm
Example

An example SQL script to create the needed tables might look somethinglike this (adapt the syntax as required for your particular database):

Lockoutrealm Tomcat 9

Tomcat

Example Realm elements are included (commented out) in thedefault $CATALINA_BASE/conf/server.xml file. Here's an examplefor using a MySQL database called 'authority', configured with the tablesdescribed above, and accessed with username 'dbuser' and password 'dbpass':

Additional Notes

Realm.lockoutrealm

JDBCRealm operates according to the following rules:

Lockoutrealm Configuration

  • When a user attempts to access a protected resource for the first time, Tomcat will call the authenticate() method of this Realm. Thus, any changes you have made to the database directly (new users, changed passwords or roles, etc.) will be immediately reflected.
  • 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 not saved and restored across sessions serialisations. Any changes to the database information for an already authenticated user will not be reflected until the next time that user logs on again.
  • 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.