Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Security and TLS

Realms and Authentication in Tomcat

Learn how Tomcat realms, tomcat-users.xml and security-constraint rules in web.xml protect URLs, and how BASIC, FORM and DIGEST login work.

A web application usually has pages that only certain people may open: an admin console, a reports section, an API for staff. Tomcat can enforce this itself, before your servlet code runs. You describe which URLs are protected and which roles may use them, and Tomcat takes care of asking for credentials, checking them and remembering the login in the session. This is called container-managed security.

Three things work together. A realm is Tomcat's source of users, passwords and roles. A security constraint in web.xml says which URL patterns need which roles. A login configuration says how the browser asks for a login. In this lesson you will see each piece, then build a small stand-in in Java so you can watch the matching rules work.

Tomcat itself cannot run on this site, so the XML and configuration below are read-only. The runnable Java examples are labelled stand-ins that mimic the rules, not the real Tomcat code.

Realms: where users come from

A realm is configured inside a <Engine>, <Host> or <Context> element in conf/server.xml. The default setup wraps a UserDatabaseRealm in a LockOutRealm, which blocks an account for a few minutes after repeated failed logins:

XML
<Realm className="org.apache.catalina.realm.LockOutRealm"
       failureCount="5" lockOutTime="300">
  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>
</Realm>

The UserDatabase resource reads conf/tomcat-users.xml. Each user has a name, a password and a comma-separated list of roles:

XML
<tomcat-users xmlns="http://tomcat.apache.org/xml" version="1.0">
  <role rolename="reports"/>
  <role rolename="admin"/>
  <user username="alice" password="s3cret" roles="reports"/>
  <user username="bob"   password="t0ps3cret" roles="reports,admin"/>
</tomcat-users>

Plain-text passwords are fine for a learning setup but not for production. Other realms let you move the data elsewhere:

Realm Where users live
UserDatabaseRealm tomcat-users.xml, loaded as a JNDI resource
DataSourceRealm a database table, through a JNDI DataSource
JNDIRealm an LDAP or Active Directory server
JAASRealm any JAAS login module
CombinedRealm several realms asked in order

To avoid plain-text passwords, add a CredentialHandler to the realm. MessageDigestCredentialHandler stores a salted hash created with bin/digest.sh -a SHA-256 -s 16 -i 100000 password, and Tomcat compares hashes on login. A realm placed in a Context protects only that application; placed in the Engine it protects everything.

Security constraints in web.xml

Inside an application, WEB-INF/web.xml declares what is protected. A constraint has a web resource collection (URLs and optionally HTTP methods), an auth constraint (the allowed roles) and optionally a user data constraint (transport rules such as HTTPS only):

XML
<security-constraint>
  <web-resource-collection>
    <web-resource-name>Reports</web-resource-name>
    <url-pattern>/reports/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
    <role-name>reports</role-name>
  </auth-constraint>
  <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>
</security-constraint>

<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>Company reports</realm-name>
</login-config>

<security-role>
  <role-name>reports</role-name>
</security-role>

CONFIDENTIAL makes Tomcat redirect plain HTTP requests to the connector's redirectPort. An <auth-constraint> with no role names blocks everyone, which is handy for hiding files; leaving out the whole element means "no login needed".

URL patterns follow the Servlet rules: an exact match wins first, then the longest path prefix (/reports/*), then an extension match (*.jsp), and finally the default /. A pattern such as /reports/* does not protect /report, a common source of holes.

Choosing the login method

  • BASIC makes the browser show its own login box and send Authorization: Basic ... (base64 of user:password, not encrypted). Use it only over HTTPS.
  • FORM shows your own HTML page. It must post j_username and j_password to j_security_check. The session keeps the login, and you can style the page.
  • DIGEST sends a hash instead of the password, but it needs passwords stored in a reversible form and is rarely used today.
  • CLIENT-CERT uses a TLS client certificate (see TLS in Tomcat).
XML
<login-config>
  <auth-method>FORM</auth-method>
  <form-login-config>
    <form-login-page>/login.html</form-login-page>
    <form-error-page>/login-error.html</form-error-page>
  </form-login-config>
</login-config>

Inside servlet code you can check the result with request.getRemoteUser(), request.isUserInRole("admin") and request.getUserPrincipal(). After a successful FORM login Tomcat changes the session id to defend against session fixation.

A runnable stand-in: matching a URL to a constraint

This stand-in reproduces the core rule: find the most specific matching pattern, then check the role. It is not Tomcat code, but it uses the same matching order.

Java Stand-in: constraint matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that /report is allowed even though /reports/* exists, and that /tools/run.jsp needs the staff role which nobody holds. The 401 versus 403 split is the same as in Tomcat: 401 asks you to authenticate, 403 means you are known but not permitted.

Hashing passwords like a credential handler

A credential handler never stores the password. It stores a random salt plus a slow hash and recomputes it at login. This stand-in uses Java's built-in PBKDF2 to show the idea:

Java Stand-in: salted password hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

MessageDigest.isEqual compares in constant time, which stops attackers from learning the hash byte by byte from timing. Tomcat's handler does the same thing for you.

Common mistakes

  • Using BASIC over plain HTTP: the password crosses the network in a trivially decoded form.
  • Forgetting <security-role> entries or mapping names that do not match the realm's roles (names are case sensitive).
  • Protecting only /admin/* but exposing the same servlet under a second mapping.
  • Leaving the default manager and host-manager roles with weak passwords (see hardening Tomcat).
  • Listing HTTP methods in a constraint: methods not listed are then unprotected. Use <http-method-omission> to be safe.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a Tomcat realm provide?

    A realm is Tomcat's source of user credentials and roles; it can be backed by a file, a database, LDAP or JAAS.
  2. 2. A request from a logged-in user without the required role gets which status?

    401 means authentication is missing or failed. A known user who lacks the role gets 403.
  3. 3. Which login method lets you supply your own styled HTML page?

    FORM login uses a page you write that posts j_username and j_password to j_security_check.
  4. 4. What does <transport-guarantee>CONFIDENTIAL</transport-guarantee> do?

    Requests for the protected URLs must arrive over a secure connection; Tomcat redirects to the connector's redirectPort.

Summary

  • Realms supply users and roles; web.xml constraints decide who may open which URLs.
  • BASIC and FORM are the common login methods; both need HTTPS to be safe.
  • Constraint matching prefers an exact path, then the longest prefix, then an extension.
  • Store hashed, salted passwords with a CredentialHandler, and wrap realms in LockOutRealm.
  • 401 means "log in"; 403 means "logged in but not allowed".

Next: TLS and HTTPS in Tomcat