Protecting a Resource with a MemoryRealm
To actually see how a MemoryRealm
works, let’s create a realm that protects a sample web application named /onjava
. At this point, if you have not already done so, take a look at my previous OnJava article, Deploying Web Applications to Tomcat. We will be using the /onjava
web application from it. The steps involved in setting up a new MemoryRealm
are described in the following list.
- Open
<tomcat_home>/conf/server.xml
and uncomment the following line.<Realm className="org.apache.catalina.realm.MemoryRealm" />
By un-commenting this
<realm>
entry, you are making theMemoryRealm
the default realm implementation for the entire default container. If you cannot find this entry, add it directly under theEngine
sub-element. - Open
<tomcat_home>/webapps/onjava/WEB-INF/web.xml
and add the following security constraint:<security-constraint>
<web-resource-collection>
<web-resource-name>OnJava Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>onjavauser</role-name>
</auth-constraint>
</security-constraint>There are only two sub-elements that you need to focus upon. The first is the
<url-pattern>
sub-element. This sub-element defines the URL pattern that will be protected by the resource. The entry you included protects the entire/onjava
Web application. The second sub-element,<role-name>
, defines the user role that can access the resource protected by the previously defined<url-pattern>
. In summary, this entire entry states that the/onjava
Web application can only be accessed by users with a defined role ofonjavauser
. - Add the following
<login-config>
sub-element directly following the<security-constraint>
.<login-config>
<auth-method>BASIC</auth-method>
<realm-name>OnJava Application</realm-name>
</login-config>The
<login-config>
sub-element defines the authentication method for the defined realm. The possible values areBASIC
,DIGEST
, andFORM
. And the<realm-name>
sub-element names the Web resource that this<login-config>
maps to. - Open
<tomcat_root>/conf/tomcat-users.xml
and add the following<user>
sub-element:<user name="bob" password="password" roles="onjavauser" />
The
<user>
sub-element you are adding will create a new user in theMemoryRealm
database with a name ofbob
, a password ofpassword
, and a role ofonjavauser
. You should notice that the value of the roles attribute matches the value of the<role-name>
sub-element of the previously-defined<security-contstraint>
. - To complete this configuration, stop and restart the Tomcat server.