Perl/CGI user authentication and session management on the Apache web server


Apache has built-in modules for user authentication: mod_auth, which is compiled into Apache by default. To use mod_auth, first make sure that your httpd.conf file is configured to allow the .htaccess file to override the settings in httpd.conf (otherwise, the httpd.conf file will determine who is and who is not allowed access to your web pages):
  1. In the main server context, make sure you have either "AllowOverride All" (possible security implications, if users can write to subdirectories) or "AllowOverride AuthConfig".
  2. In the users' home directories context ("Directory /home/*/public_html"), set "AllowOverride AuthConfig" or "AllowOverride All" as desired.
  3. For the cgi-bin directory configuration, set "AllowOverride All" or "AllowOverride AuthConfig", as desired.
  4. Restart the apache server:
    1. /usr/sbin/apachectl configtest
    2. /usr/sbin/apachectl restart

To tell Apache which users are allowed to access your web pages, you must create two files: .htaccess and .htpasswd. .htaccess defines each realm it covers, lists the path to the .htpasswd file, and lists the users that are allowed access. .htpasswd matches the user name with the password that allow the user to authenticate.
Suppose you have a web server with the document root /usr/home/me/www (because it is a tilde directory on a Unix server), and you want to allow the users "me", "friend" and "coworker" access to your web pages. In the directory /usr/home/me/www you will create a file .htaccess:
                  vi /usr/home/me/www/.htaccess
                
The contents of the file should look like this:
                  AuthName        "Home Directory"
                  AuthType Basic
                  AuthUserFile /usr/home/me/www/.htpasswd
                  require user me friend coworker
                

You may change the path for AuthUserFile to any path to which you have write access.
From the command line, type
                  htpasswd -c /usr/home/me/www/.htpasswd me
                  htpasswd /usr/home/me/www/.htpasswd friend
                  htpasswd /usr/home/me/www/.htpasswd coworker
                

Congratulations! You now have created user authentication on your Apache server. Please note, however, that the .htaccess file will apply to the directory in which you placed it, and also to any subdirectories! If you wish to lock subdirectories down even more, you will need to create new .htaccess files within those subdirectories. If the users will have the same passwords to access subdirectories, you need not change the AuthUserFile path.