Authentication guide - novalexei/mod_servlet GitHub Wiki

Authentication guide

Authentication is what nearly every web application requires. Java Servlet containers provide several types of authentication. mod_servlet by itself doesn't implement any authentication methods. But Apache2 server does and mod_servlet seamlessly picks up this information. Apache2 has a number of modules to handle authentication: mod_auth_basic, mod_auth_digest, mod_auth_form and bunch of others, including database ones.

Let's try to configure web site with secure area. To do so we will use the simplest basic authentication.

  1. First, generate password file:

    htpasswd -c /path/to/my/passwdfile user1
  2. Configure httpd.conf file.

    2.1 Make sure auth_basic_module enabled:

    LoadModule auth_basic_module modules/mod_auth_basic.so

    2.2 In the Location section where we set SetHandler servlet add these instructions:

    AuthType basic
    AuthName "private area"
    AuthBasicProvider file
    AuthUserFile /path/to/my/passwdfile
    Require valid-user

Now the server is ready to authenticate you. But before that we need a servlet to see our authentication information:

class check_principal_servlet : public http_servlet
{
public:
    void do_get(http_request& req, http_response& resp) override
    {
        auto p = req.get_session().get_principal();
        resp.set_content_type("text/html");
        std::ostream &out = resp.get_output_stream();
        out << "<!DOCTYPE html>\n"
               "<html>\n"
               "<head>\n"
               "<title>Principal</title>\n"
               "</head>\n"
               "<body>\n"
               "<p>Request path is: " << req.get_path_info() << "</p>";
        if (p) out << "<p>Session principal is: " << p->get_name() << "</p>\n";
        else out << "<p>No session principal</p>\n";
        out << "</body>\n"
               "</html>\n";
    }
}
SERVLET_EXPORT(checkPrincipalServlet, check_principal_servlet)

As you can see this servlet reports current request URL and authenticated principal name if it exists. Compile and install this servlet. Remove all other servlets and filters form web.xml deployment descriptor. Restart Apache server and go to the servlet's URL.

If you followed previous steps meticulously you'll see the login dialog. Enter user and password you created on the step 1. and you will be let in. On the servlet page you should see the name of user you've just entered.

Victory! If you got this far you are ready to write Custom Authentication Filter

To The Programming Guide

⚠️ **GitHub.com Fallback** ⚠️