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
- configure a realm
- define the parts of your web page that should be secured in the
- 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:
- Clone the Maven project from GitHub and build the JAR
- Copy the JAR into the tomcat /lib folder
- Add the following entry to the
<Realm authDB="db-containing" authCollection="users" authUserField="username" authPasswordField="password" authRoleField="" className="de.locked.tomcat.mongorealm.GenericMongoRealm" defaultDbHost="localhost" defaultDbPass="" defaultDbUser="" defaultRole="user" digest = "SHA-256"/>
- Activate the password protection in
<security-constraint> <web-resource-collection> <web-resource-name>auth</web-resource-name> <url-pattern>/api/auth/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>user</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>Basic Authentication</realm-name> </login-config> <security-role> <role-name>user</role-name> </security-role>
- If you don’t want to enter the database credentials in the XML, you can also set environment variables:
OPENSHIFT_MONGODB_DB_HOST, OPENSHIFT_MONGODB_DB_USERNAME, OPENSHIFT_MONGODB_DB_PASSWORD