TomEE is of course able to reuse Tomcat realms but one limitation of Tomcat is the need to provide it in the container (understand it is not designed to be provided in the webapp).
TomEE proposes a small tip regarding this topic.
Tomcat and TomEE create the realm before deploying the application (in the “config phase”) so the classloader of the webapp is not available to get the realm inside. That’s why the basic idea is to delay the instantiation of the real Realm.
Note: the little limitation is to use the realm from the webapp (no JMX etc…). Not a big deal for almost all applications.
To delay you realm instantiation you simply declare a particular Realm called org.apache.tomee.catalina.realm.LazyRealm.
To be able to set the properties of your realm you can use the property properties of the LazyRealm. This way the configuration will be propagated to the delegated realm.
<?xml version="1.0" encoding="UTF-8"?> <Context antiJARLocking="true" path="/my-app"> <Realm className="org.apache.tomee.catalina.realm.LazyRealm" realmClass="org.foo.MyRealm" properties=" someAttribute=value someOtherAttribute=another" /> </Context>
It is already not that bad but we can go a little bit further. There is another (boolean) property to the LazyRealm called cdi. If you set it to true the properties attribute is ignored but the realm is looked up through the BeanManager. So using CDI the configuration lokos like:
<?xml version="1.0" encoding="UTF-8"?> <Context antiJARLocking="true" path="/my-app"> <Realm className="org.apache.tomee.catalina.realm.LazyRealm" realmClass="org.foo.MyRealm" cdi="true" /> </Context>