Interview Questions

Tomcat Authentication

In this article we will discuss about providing basic authentication in tomcat web server.

Web applications deployed in web servers require restricted access. Either the authentication may be provided in the application level or it may be provided by the web/application server.

In general there are four types of authentication supported by web containers

1. BASIC - Were the login info is transmitted to server using base64 encoding

2. FORM - User authentication form is displayed to get the login credentials from user and transmitted to the server using HTTP request with out any encryption

3. DIGEST - Transmits the credentials in a secure way, but not supported by many J2ee web containers

4. CLIENT-CERT - is the most secured form of authentication as it uses Public Key Certificates for securing user credentials, but client needs a certificate to logging into the server

Lets see the support provided by tomcat server for BASIC authentication.

1. Create a DB table to store userName/Password.


2. Open server.xml available in conf/ directory inside the tomcat installation directory.

3. Copy the following tag in the server.xml file.

server.xml Creation

<Realm className="org.apache.catalina.realm.JDBCRealm" driverName="driverName" connectionURL="jdbc-url" connectionName="" connectionPassword="" userTable="USER_CREDENTIALS" userNameCol="USER_NAME" userCredCol="PASS_WORD" />

The above tag is used to verify the username/password with the one provided by client to login in to the web application. The DB details where the newly created USER_CREDENTIALS table containing username/password along with the column name should be provided in the tag above.

4. Also copy the jdbc driver (*.jar) file in to the tomcat lib/ directory, so that the container can connect to the DB.

5. Open web.xml of any web application to which you want to provide authentication from the web container.

6. Copy the following tags in the web.xml file


        <web-resource-name> Entire Application </web-resource-name>




The security constraint tag specifies the web resource or the URL pattern in the web application which need to be authenticated. tag specifies the mode of authentication. In this case it is BASIC. tag specifies the list of roles present. In the above case we used '*' so that all roles are permitted.

Now if the client access the web application in the restricted URL pattern, a browser specific authentication dialog box will be opened ,prompting userName/password. Then the user credentials will be verified with the DB by the web container with the information provided in server.xml. If there is a mismatch of user credentials then the client will not be able to access the web application.

In this way BASIC authentication support is provided by tomcat web container.