Tomcat MongoDB Authentication Realm

Tomcat MongoDB Authentication Realm

Tomcat provides a nice and powerful mechanism for authentication by the so called Tomcat Authentication Realms.
In the Tomcat Docs, Realms are explained as:

A Realm is a “database” of usernames and passwords that identify valid users of a web application (or set of web applications), plus an enumeration of the list of roles associated with each valid user. You can think of roles as similar to groups in Unix-like operating systems, because access to specific web application resources is granted to all users possessing a particular role (rather than enumerating the list of associated usernames). A particular user can have any number of roles associated with their username.

Tomcat comes already with several Realms like JDBC, JNDI JDBC, XML, Memory, JNDI and JAAS (all explained in the docs). The nice advantage of such realms is that you don’t have to care a lot about auth checks in the code itself. You just

  1. configure a realm
  2. define the parts of your web page that should be secured in the web.xml
  3. add a login page with the login and password fields having special names and a special post-URL

and — that’s it!

Sounds great! As I am playing around with MongoDB, I of course wanted to use a MongoDB Realm so that I am able to use user and password information directly from MongoDB.

Unfortunately I didn’t find a ready to use Mongo Realm that was generic enough for my needs. So I made my own one.
After digging a bit into the authentication realm code and examples I built a generic Mongo Authentication Realm which should be flexible enough to either cover quite some MongoDB cases or provide a starting ground for modifications.

Installing is rather easy:

  1. Clone the Maven project from GitHub and build the JAR
  2. Copy the JAR into the tomcat /lib folder
  3. Add the following entry to the context.xml:
        digest = "SHA-256"/>
  4. Activate the password protection in web.xml:
        <realm-name>Basic Authentication</realm-name>
  5. If you don’t want to enter the database credentials in the XML, you can also set environment variables: