Search code examples
javaauthenticationtomcattomcat9

How to define UserDatabase in Tomcat within a Context xml file?


I have been experimenting with setting up authentication with Tomcat config by only setting a context file.

Given the following webapp context file conf/Catalina/localhost/myapp.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Resource
      name="MyUserDatabase"
      auth="Container"
      type="org.apache.catalina.UserDatabase"
      factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
      pathname="conf/myapp-users.xml"
      />
  <Realm
      className="org.apache.catalina.realm.UserDatabaseRealm"
      resourceName="MyUserDatabase"
      />
</Context>

When starting Tomcat, it gives the following error:

javax.naming.NameNotFoundException: Name [MyUserDatabase] is not bound in this Context. Unable to find [MyUserDatabase].

However, if I define <Resource name="MyUserDatabase"... in server.xml under <GlobalNamingResources> it works as expected. The documentation for contexts clearly shows the <Resource> element is valid there.

Is there a special way to reference resources defined in a context file? Or is it just not possible?

In-case it matters, I am dealing with Tomcat 9.


Solution

  • You need to add the property localJndiResource="true" to your realm:

    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="MyUserDatabase"
           localJndiResource="true"/>
    

    Without this property Tomcat looks for a resource in <GlobalNamingResources> (cf. Tomcat documentation).