Setting up Apache Tomcat basic authentication using the DataSourceRealm on CentOS 6 with MySQL

Post to Twitter

Today I’m going to take a clean CentOS 6.0 system and build it up so it runs Apache Tomcat 6 with basic authentication using the DataSourceRealm. You can read more about realm configuration on the Apache Tomcat website.


From the command prompt on CentOS 6 enter the following commands to install the Java OpenJDK (you can use Oracle’s JDK if you wish), Tomcat 6 (you can use the newer Tomcat 7 if you want) and MySQL.

$ sudo yum install java-1.6.0-openjdk
$ sudo yum install tomcat6
$ sudo yum install mysql-server
$ service mysqld start

Let’s secure MySQL a little bit. Run the following command:

$ sudo /usr/bin/mysql_secure_installation

Change root password then answer yes to everything else.

Configure MySQL to start after a reboot by doing this:

$ sudo chkconfig mysqld on

We will create the two tables required by Tomcat’s DataSourceRealm according to the structure they show in their documentation. Feel free to normalize this script if you wish, a good start is the scheme defined on this site (it should work as well but I haven’t tested it).

DROP DATABASE IF EXISTS tomcat_realm;
CREATE DATABASE tomcat_realm;
USE tomcat_realm;
CREATE TABLE tomcat_users (
        user_name varchar(20) NOT NULL PRIMARY KEY,
        password varchar(250) NOT NULL
);
CREATE TABLE tomcat_roles (
        user_name varchar(20) NOT NULL,
        role_name varchar(20) NOT NULL,
        PRIMARY KEY (user_name, role_name) 
);
INSERT INTO tomcat_users (user_name, password) VALUES ('someuser', '5f4dcc3b5aa765d61d8327deb882cf99');
INSERT INTO tomcat_roles (user_name, role_name) VALUES ('someuser', 'authenticated');
COMMIT;

Save that SQL script in your Documents folder as: createdb.sql.

Go into MySQL and create the database as well as a user that has real-only access to the new tables:

$ mysql -u root -p
mysql> SOURCE ~/Documents/createdb.sql
mysql> use tomcat_realm;
mysql> show tables;
mysql> CREATE USER 'realm_access'@'localhost' IDENTIFIED BY 'password';
mysql> GRANT SELECT ON tomcat_realm.* TO realm_access@localhost;

Note: I’ve already converted the string password to it’s MD5 equivalent.

The next step is to grab the MySQL JDBC Driver from: http://dev.mysql.com/downloads/connector/j/

Assuming your in your home directory Documents folder:

$ cd .. && cd Downloads
$ wget http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.17.zip/from/http://mysql.mirrors.hoobly.com/

Extract the file:

$ unzip mysql-connector-java-5.1.17.zip

We will need the jar file in a bit. First, let’s setup the Tomcat configuration.

$ cd /usr/share/tomcat6/conf
$ sudo nano server.xml

Add in the DataSourceRealm as per: http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html#DataSourceRealm

Comment out the Following:

<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

Add the following (also I’ve shown the commented out part):

<!--
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
-->
<Realm className="org.apache.catalina.realm.DataSourceRealm"
   dataSourceName="jdbc/auth"
   digest="MD5"
   userTable="tomcat_users" userNameCol="user_name" userCredCol="password"
   userRoleTable="tomcat_roles" roleNameCol="role_name"/>

Save and exit the file.

Note: For the digest you can use: SHA, MD2, or MD5

Move the MySQL JDBC Jar file to Tomcat’s lib folder:

$ cd .. && cd lib
sudo mv ~/Downloads/mysql-connector-java-5.1.17/mysql-connector-java-5.1.17-bin.jar mysql-connector-java-5.1.17-bin.jar

Now we need to create a JNDI datasource: http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

$ cd .. && cd conf
$ sudo nano context.xml

Between the context elements add this:

<Resource name="jdbc/auth" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="realm_access" password="password" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/tomcat_realm"/>

Save and exit the file.

Note: You could also put this in the server.xml file if you want global web app visibility.

Create a new Maven Java Project (WAR) in Netbeans 7. You don’t need to do anything fancy other than edit the web.xml file like below (edit as required by your own project settings):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>DemoServlet</servlet-name>
        <servlet-class>com.giantflyingsaucer.tomcatsecurity.DemoServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DemoServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Wildcard means whole app requires authentication</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>DELETE</http-method>
            <http-method>PUT</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>authenticated</role-name>
        </auth-constraint>
    </security-constraint>   
    
    <security-role>
        <role-name>authenticated</role-name>
    </security-role>    

    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>tomcat_realm</realm-name>
    </login-config>
</web-app>

I removed the default JSP page that Maven generates and replaced it with a servlet like this:

package com.giantflyingsaucer.tomcatsecurity;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet DemoServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet DemoServlet</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

Clean and Build the new project and take the resulting war file and rename it to: ROOT.war

Take the ROOT.war file and move it to this location:

/usr/share/tomcat6/webapps

Start Tomcat 6:

$ sudo service tomcat6 start

Note: Don’t ever start Tomcat with sudo in production, instead create a tomcat user and follow the best practices on the Tomcat website.

Browse to: http://localhost:8080

Username: someuser
Password: password

Result:

You can tweak this a fair amount, this is just the basics but can serve as a starting point.

One final point to make is that unless you use SSL the username and password in this technique will be sent over clear text. You should also look into implementing the LockOutRealm to assist in protecting from brute force scripted attacks.

Post to Twitter

This entry was posted in Apache Tomcat, Java, Netbeans, Open Source. Bookmark the permalink.

One Response to Setting up Apache Tomcat basic authentication using the DataSourceRealm on CentOS 6 with MySQL

  1. Pingback: Setting up Apache Tomcat basic authentication using the DataSourceRealm for Atom Hopper | Giant Flying Saucer

Comments are closed.