2

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.

kazza
  • 365
  • 3
  • 11

1 Answers1

4

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).

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43
  • 1
    I confirm it works! - Thanks, I spent ages reading the docs, but alas not the right bit. – kazza Jan 29 '21 at 09:10