Wednesday, July 1, 2009

Password protected application in tomcat server

We can do container level authentication in tomcat server. Tomcat support three types of authentication. DataSourceRealm, JDBCRealm, JNDIRealm, MemoryRealm. For more detail...

we will see implementation of "MemoryRealm". This uses XML file as the source to maintain the username and password.

You can see /conf/tomcat-users.xml file contains the username, password and roles.

Step 1:
You can add new user and roles as follows
<?xml version='1.0' encoding='utf-8'?>
<role rolename="manager"/>
<role rolename="admin"/>
<role rolename="ananymous">
<user username="tomcat" password="tomcat" roles="manager,admin"/>
<user username="newuser" password="password" roles="ananymous"/>

Step 2:
Next thing Enable MemoryRealm in the <tomcat-home>/conf/server.xml file.
By default UserDatabaseRealm is enabled. Comment out this and add the add the MemoryRealm <Realm className="org.apache.catalina.realm.MemoryRealm" />

Step 3:
Have to add the security-constraint in our application's web.xml file. Assume that we have deployed "webapplication1" in tomcat[<tomcat-home>/webapp/webapplication1].
We need to add following security-constraint in <tomcat-home>/webapp/webapplication1/WEB-INF/web.xml.

<web-resource-name>Tomcat User authentication</web-resource-name>
<realm-name>Tomcat User authentication</realm-name>

Role <role-name>anonymous</role-name> applied for all request comes to the webapplication1 for the url-pattern <url-pattern>/*</url-pattern>.

If tomcat container encounter the security-constraint in the web.xml for the given request, it add the authentication header in the response. So broswer popups the window to receive username and password.

IF username and password matches in the tomcat-users.xml, container allow the access the resource.

<auth-method>BASIC</auth-method> defines the authentication method to define the Realm. The possible values are BASIC, DIGEST and FORM.

If our application uses some other security, tomcat MemoryRealm may give issues.


Post a Comment