Using the MemoryRealm

The following example will create a web application containing a jsp that will behave based on who is logged in. The possible users that can be logged in will be defined in an xml file called tomcat-users.xml located in the [TOMCAT-HOME]/conf directory.

This example will recognize two types of custom defined roles: GOLD and SILVER roles. Every user will be assigned one or both roles.

1. Create the following xml file in the [TOMCAT-HOME]/conf directory: tomcat-users.xml (or add the user tags to the existing tomcat-users.xml file):

<tomcat-users>
  <user name="gary"    password="yrag"   roles="gold"/>
  <user name="alicia"  password="aicila" roles="gold"/>
  <user name="john"    password="nhoj"   roles="silver"/>
  <user name="joris"   password="siroj"  roles="gold,silver"/>
</tomcat-users>

2. The JSP is as simple as it can be. It prints out the user that is logged in and prints out to which role it belongs.

confidential.jsp:

<html>
<body>
Hi, <%=request.getUserPrincipal().getName()%><br><br>
<%
   if (request.isUserInRole("gold")) {
%>
      You have the GOLD role<br>
<%
   }
   if (request.isUserInRole("silver")) {
%>
      You have the SILVER role<br>
<%
   }
%>
</body>
</html>

3. Create the WEB-INF/web.xml deployment descriptor.

<?xml version="1.0" encoding="ISO-8859-1"?>
 
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
 
<web-app>
   <security-constraint>
      <web-resource-collection>
         <web-resource-name>admin</web-resource-name>
         <url-pattern>*.jsp</url-pattern>
      </web-resource-collection>
      <auth-constraint>
         <role-name>gold</role-name>
         <role-name>silver</role-name>
      </auth-constraint>
   </security-constraint>
   <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>Log In</realm-name>
   </login-config>
</web-app>

This deployment descriptor specifies that only users with roles gold or silver are authorized to access the *.jsp resources. The method of authorization is BASIC. Other possible authorization methods are DIGEST and FORM (see other Q/A’s for examples).

4. Now package everything up in a web application loginexample1.war:

C:loginexample1>jar -cvf loginexample1.war *
added manifest
adding: confidential.jsp(in = 275) (out= 160)(deflated 41%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/web.xml(in = 673) (out= 328)(deflated 51%)

and drop loginexample1.war into the /webapps directory.

5. Start up Catalina and point your browser to http://localhost:8080/loginexample1/confidential.jsp.

Because a security constraint is defined in web.xml, specifying that only gold and silver roles can access all jsp pages, and because BASIC authentication is specified, the following window will popup to ask for the username and password:

Try one of the entries in tomcat-users.xml. Notice that you cannot log out, except by closing the browser window.