Yolinux.com Tutorial

Apache Web Login Authentication:

Adding password protection to a web site using Apache web server authentication.


Apache authentication can be configured to require web site visitors to login with a user id and password. This is different than adding a login form on a web page and creating your own authentication. This tutorial describes the various methods available for authentication with Apache and its' configuration. Login protection is applied to the web pages stored in a directory. The login dialog box which requests the user id and password is provided by the web browser at the request of Apache. Apache allows the configuration to be entered in its' configuration files (i.e. main configuration file /etc/httpd/conf/httpd.conf, supplementary configuration files /etc/httpd/conf.d/component.conf or in a file which resides within the directory to be password protected. Five forms of authentication are detailed here: Apache password file authentication, digest file authentication, LDAP, NIS and MySQL.

Apache authentication methods using local files to store passwords, have no association with system user accounts. If using LDAP or NIS for system login authentication, its use can be extended to support Apache web site logins.

Apache configuration files: (refered to generically in this tutorial as httpd.conf or reside as the file .htpasswd, in the directory being protected.)

Tutorial Table of Contents:


Related YoLinux Tutorials:

°Web Site Configuration

°Apache Authentication

°NIS configuration

°LDAP server configuration

°Linux LDAP authentication

°Apache Redirect

°Internet Security

°Disc Quotas

°YoLinux Tutorials Index



Free Information Technology Magazine Subscriptions and Document Downloads


Apache password file authentication:

Directory protection using .htaccess and .htpasswd

This tutorial applies to Apache based web servers. It requires:

  1. Editing the server configuration file (httpd.conf) to enable/allow a directory structure on the server to be password protected. Basically the default <Directory> access permission statement need modification.
  2. The creation and addition of two files specifying the actual logins and passwords. (.htaccess and .htpasswd)

Use this sparingly because Apache will have to check all directories and subdirectories specified in the configuration file for the existence of the .htaccess file adding to a servers latency.

When trying to access a file in a protected directory, the user will be presented with a window (dialog box) requesting a username and password. This protection applies to all sub-directories. Other .htaccess files in sub directories may respecify access rules.

Apache authentication uses the modules mod_auth and mod_access.


Apache configuration file:

File: /etc/httpd/conf/httpd.conf (older systems used access.conf)

Default: This disables the processing of .htaccess files for the system.

     <Directory />
AllowOverride None
</Directory>

or for a specified directory:

     <Directory /home/domain/public_html>
AllowOverride None
</Directory>

Change to and/or specify directory to protect:

     <Directory /home/domain/public_html/membersonly>
AllowOverride All
</Directory>
OR
     <Directory /home/domain/public_html/membersonly>
AllowOverride AuthConfig
</Directory>

AllowOverride parameters: AuthConfig FileInfo Indexes Limits Options

The name of the "distributed" and user controlled configuration file .htaccess is defined with the directive: (default shown)

 AccessFileName .htaccess


Password protection by a single login:

Password files:

  1. Create the directory you want to password protect (example: membersonly)
  2. Create a file /home/domain/public_html/membersonly/.htaccess in that director that looks something like this:
         AuthName "Add your login message here."
    AuthType Basic
    AuthUserFile /home/domain/public_html/membersonly/.htpasswd
    AuthGroupFile /dev/null
    require user name-of-user
    In this case the "name-of-user" is the login name you wish to use for accessing the web site.

    [Pitfall] The literature is full of examples of the next method but I never got it to work.

    One can use Apache directives to specify access and restriction:

         AuthName "Add your login message here."
    AuthType Basic
    AuthUserFile /home/domain/public_html/membersonly/.htpasswd
    AuthGroupFile /dev/null
    <Limit GET POST>
    require user name-of-user </Limit>

    Also see: List of Apache directives. If an incorrect directive is used in the .htaccess file it will result in a server error. Check your log files: /var/log/httpd/error_log.
    The name of the access file .htaccess is specified by the httpd.conf directive AccessFileName.

  3. Create the password file /home/domain/public_html/membersonly/.htpasswd using the program htpasswd:
             htpasswd -c .htpasswd name-of-user
              
    Man page: htpasswd

    Example file: .htpasswd

    user1:KgvCSeExtS4kM
    USER1:KgvCSeExtS4kM
    User1:KgvCSeExtS4kM


Flexible password protection by group access permissions:

This example differs from the previous example in that it allows for greater control and flexibility by using groups.

Password files:

  1. Create a file .htgroup in that directory that contains the groupname and list of users:
          member-users: user1 user2 user3 ... etc

    Where member-users is the name of the group.

  2. Modify .htaccess in the membersonly directory so it looks something like:
          AuthName "Add your login message here."
    AuthType Basic
    AuthUserFile /home/domain/public_html/membersonly/.htpasswd
    AuthGroupFile /home/domain/public_html/membersonly/.htgroup
    require group member-users
  3. Create the password file .htpasswd using the program htpasswd for each user as above. You don't need the -c option if you are using the same .htpasswd file. (-c is only to create a new file)
             htpasswd -c /home/domain/public_html/membersonly/.htpasswd user1
    htpasswd /home/domain/public_html/membersonly/.htpasswd user2


Restrict access based on domain or IP address:

Allow specified domain to access site:

Order deny, allow
Deny from all
Allow from allowable-domain.com
Allow from XXX.XXX.XXX Deny from evil-domain.com
Specify first three (or one, or two, ...) octets of IP address defining allowable domain.


Placing Authentication directives in httpd.conf exclusively instead of using .htaccess:

The purpose of using the "distributed configuration file" .htaccess is so that users may control authentication. It can also be set in the Apache configuration file httpd.conf WITHOUT using the .htaccess file. This can improve server performance as the server will not have to look for the .htaccess file in each subdirectory.

File: httpd.conf (portion)
    ..
...

<Directory /home/domain/public_html/membersonly>
AllowOverride AuthConfig
AuthName "Add your login message here."
AuthType Basic
AuthUserFile /home/domain/public_html/membersonly/.htpasswd
AuthGroupFile /dev/null
require user name-of-user </Directory> ... ..

Perl CGI Script to Modify User Passwords:

This allows users to manage / change their own passwords.

Use the Perl CGI script htpasswd.pl [cache]

  • Edit location of Perl .i.e.: /usr/bin/perl
    Not /usr/local/bin/perl
  • Edit the script to specify location of the password file i.e. /var/www/PasswordDir/.htpasswd
  • SELinux users must add the correct attribute i.e. chcon -R -h -t httpd_sys_content_t /var/www/PasswordDir
  • The password file must be located in a directory where CGI is allowed to modify files.
    File: httpd.conf (portion)
        ..
    ...

    <Directory "/var/www/PasswordDir">
    Options -Indexes
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
    </Directory>
    ...
    ..


Using Digest File for Apache Authentication:

This method authenticates a user login using Apache 2.0 on Linux. The logins have no connection to user accounts.

<Location /home/domain/public_html/membersonly>
AuthType Digest
AuthNAme "Members Only Area"
AuthDigestDomain /home/domain/public_html/membersonly AuthDigestFile /etc/httpd/conf/digestpw require valid-user </Location>
For more on digest authentication see:


Using LDAP for Apache Authentication:

This method authenticates using Apache 2.0 and mod_auth_ldap on Linux (supplied by default with RHEL4, CentOS4, FC3 RPM package mod_auth_ldap) and an LDAP server. LDAP can be used to authenticate user accounts on Linux and other computer systems as well as web site logins. Also see YoLinux TUTORIAL: LDAP system authentication.

Try this out with your Apache server authenticating to our open LDAP server using our Three Stooges example.

Authenticate to an Open LDAP server. (No bind name/password required to access LDAP server)

File: httpd.conf (portion)
    ..
...

<Directory /var/www/html>
AuthType Basic
AuthName "Stooges Web Site: Login with email address"
AuthLDAPURL ldap://ldap.yo-linux.com:389/o=stooges?mail
require valid-user

</Directory>
...
..
or create the file /var/www/html/.htaccess
AuthName "Stooges Web Site: Login with email address"
AuthType Basic
AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?mail
require valid-user

Point your browser to http://localhost/
Login with the user id "LFine@isp.com" and password "larrysecret".
You will be asked to use a user id (email address) and password to enter the site.

Bind with a bind DN: (password protected LDAP repository)

File: httpd.conf (portion)
    ..
...

<Directory /var/www/html>
AuthType Basic
AuthName "Stooges Web Site: Login with email address"
AuthLDAPEnabled on
AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?mail
AuthLDAPBindDN "cn=StoogeAdmin,o=stooges"
AuthLDAPBindPassword secret1
require valid-user

</Directory>
...
..
Examples:
  • require valid-user: Allow all users if authentication (password) is correct.
  • require user greg phil bob: Allow only greg phil bob to login.
  • require group accounting: Allow only users in group "accounting" to authenticate.
For this LDAP authentication example to work, configure your LDAP server with our YoLinux Three Stooges example and set the password in the /etc/openldap.slapd.conf file.

This example specified the use of the email address as a login id. If using user id's specify:

AuthLDAPURL ldap://ldap.your-domain.com:389/o=stooges?uid

Authenticating with Microsoft Active directory using Microsoft's "Unix services for Windows":

AuthLDAPURL ldap://ldap.your-domain.com:389/ou=Employees,ou=Accounts,dc=sos,dc=com?sAMAccountName?sub
Also note that encrypted connections will use the URL prefix "ldaps://" and the added directives:
  • LDAPTrustedCA directory-path/filename
  • LDAPTrustedCAType type
    Where the "type" is one of:
    • DER_FILE: file in binary DER format
    • BASE64_FILE: file in Base64 format
    • CERT7_DB_PATH: Netscape certificate database file

Restart Apache after editing the configuration file: service httpd restart for configuration changes to take effect.
See /var/log/httpd/error_log for configuration errors.

Links:

Other LDAP modules:


Using NIS for Apache Authentication:

This method authenticates using Apache 2.0 on Linux (RHEL4, CentOS4, FC3) and an NIS server. The advantage of using NIS, is the comonality of computer system accounts and web site logins. This configuration requires that the system the Apache web server is running on, must be using NIS authentication for system logins.

This requires a NIS server. See the YoLinux.com NIS configuration tutorial.

Use the Perl module Apache-AuthenNIS.

Requires the following Perl modules:

  • ExtUtils-AutoInstall
  • Net-NIS
  • Apache-AuthenNIS

Download / Install Perl modules:

Or install from CPAN via the internet:

  • perl -MCPAN -e shell
    (Answer no)
  • install ExecUtils::AutoInstall
  • install Net::NIS
  • install Apache::AuthenNIS
  • quit

Test Perl module:

File: testAuthenNIS.pl
#!/usr/bin/perl
BEGIN{push @INC, "/usr/lib/perl5/site_perl/5.8.5/Apache";}
eval "use Apache::AuthenNIS"; $hasApacheAuth = $@ ? 0 : 1;
printf "Apache::AuthenNIS". ($hasApacheAuth ? "" : " not") . " installed";
printf "\n";
Test: [root]# ./testAuthenNIS.pl
  • Good: Apache::AuthenNIS installed
  • Not good: Apache::AuthenNIS not installed
Apache Configuration File: httpd.conf (portion)
..
...

<Directory /home/domain/public_html/membersonly>
AuthType Basic
AuthName "Add your login message here."
PerlAuthenHandler Apache::AuthenNIS
PerlSetVar AllowAlternateAuth no
require user name-of-user </Directory> ... ..
Examples:
  • require valid-user: Allow all users if authentication (password) is correct.
  • require user greg phil bob: Allow only greg phil bob to login.
  • require group accounting: Allow only users in group "accounting" to authenticate.

Example showing password protection for user web directories:

..
...

<IfModule mod_userdir.c>
UserDir public_html
</IfModule>

<Directory /home/*/public_html>
AuthType Basic
AuthName "Add your login message here."
PerlAuthenHandler Apache::AuthenNIS
PerlSetVar AllowAlternateAuth no
require user valid-user AllowOverride FileInfo AuthConfig Limit Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec <Limit GET POST OPTIONS> Order allow,deny Allow from all </Limit> <LimitExcept GET POST OPTIONS> Order deny,allow Deny from all </LimitExcept> </Directory> ... ..
Also see YoLinux SysAdmin: Perl Admin

Links:


CGI to allow users to modify their NIS Passwords:

For those users who get a shell of /sbin/nologin, the "cgipaf" web interface is ideal for user management of NIS passwords. Cgipaf uses PHP, cgi (written in C) and your system PAM authentication (or /etc/passwd, /etc/shadow files). Cgipaf also can manage mail accounts using procmail.

Download from http://www.wagemakers.be/english/programs/cgipaf

Installation/configuration:

  • tar xf cgipaf-1.3.1.tar.gz
  • cd cgipaf-1.3.1/
  • ./configure --bindir=/var/www/cgi-bin --datadir=/srv/cgipaf --sysconfigdir=/etc/cgipaf --prefix=/opt
    Note: nothing ends up in /opt
  • make
  • make install
  • cd /srv/cgipaf
  • ln -s cgipasswd.php index.php

File: /etc/httpd/conf.d/cgipaf.conf (Red Hat style systems)

Alias /NIS/ "/srv/cgipaf/"

<Directory "/srv/cgipaf">
SSLRequireSSL
Options Indexes FollowSymLinks
AllowOverride None
Order allow, deny
Allow from all
</Directory>
Note the Apache 2 directive "SSLRequireSSL" will only allow https encrypted access. This is important when managing passwords over the web.

The PHP pages reside in /srv/cgipaf/. The compiled C cgi will reside in /var/www/cgi-bin. The configuration file will be /etc/cgipaf/cgipaf.conf.

See the web page at http://localhost/NIS/


Using a MySQL database for Apache Authentication:

Two Apache modules are available for database authentication:

  • MySQL: mod_auth_mysql (This tutorial)
    • Red Hat RPM package: mod_auth_mysql
    • SuSE RPM package: apache2-mod_auth_mysql
  • DBM database file: mod_auth_dbm
    (Fast even for 1000's of users.)
Apache Configuration:
  • Red Hat: /etc/httpd/conf/httpd.conf or /etc/httpd/conf.d/application.conf
  • SuSE: /etc/apache2/httpd.conf or /etc/apache2/conf.d/application.conf
    ..
...

<Directory /home/domain/public_html/membersonly>
AuthType Basic
AuthName "Add your login message here."
AuthMySQLHost localhost AuthMySQLUser db_user AuthMySQLPassword db_password AuthMySQLDB database_name_used_for_authentication AuthMysqlUserTable http_auth AuthMySQLEnable on require valid-user </Directory> ... ..
Examples:
  • require valid-user: Allow all users if authentication (password) is correct.
  • require user greg phil bob: Allow only greg phil bob to login.
  • require group accounting: Allow only users in group "accounting" to authenticate.

Directives:

Directive Description
AuthMySQLEnable On If 'Off', MySQL authentication will pass on the authentication job to the other authentication modules i.e password files.
AuthMySQLHost host_name Name of MySQL Database hosr. i.e. 'localhost'
AuthMySQLPort TCP_Port_number Port number of MySQL Database. Default: 3306
AuthMySQLDB database_name Name of MySQL Database.
AuthMySQLUser user_id MySQL Database login id.
AuthMySQLPassword user_password MySQL Database login password. Plain text.
AuthMySQLUserTable user_table_name Name of MySQL Databse table in the database which holds the user name and passwords.
AuthMySQLGroupTable group_table_name Databse table holding group info.
AuthMySQLNameField user_field_name If not using default field name 'user_name', then specify. Not case sensitive id CHAR or VARCHAR.
AuthMySQLPasswordField password_field_name If not using default field name 'user_passwd', then specify. Passwords are case sensitive.
AuthMySQLGroupField group_field_name If not using default field name 'groups', then specify.
AuthMySQLNoPasswd Off Off: Passwords can be null ('').
On: password must be specified.
AuthMySQLPwEncryption none Options: none, crypt, scrambled (MySQL password encryption), md5, aes, sha.
AuthMySQLSaltField salt_string mysql_column_name Salt field to be used for crypt and aes.
AuthMySQLAuthoritative on Authenticate using other authentication modules after the user is successfully authenticated by the MySQL auth module. Default on: request is not passed on.
AuthMySQLKeepAlive Off Off: Close the MySQL link after each authentication request.

MySQL Admin:

  • mysqladmin -h localhost -u root -ppassword create http_auth
  • mysql -h localhost -u root -ppassword
  • mysql> use http_auth
  • mysql> create table mysql_auth ( user_name char(30) NOT NULL,user_passwd char(60) NOT NULL,user_group char(25),primary key (user_name) );
  • mysql> insert into mysql_auth values('Fred','supersecret','worker');

Links:


Login URL Tricks:

Here is a trick to incorporate a login and password into a URL. Typicall one would attempt to enter the password protected area of the web site and the user would be confronted with a login dialog box into which one would enter the user id and password. Another option is to enter a URL with the login and password embedded.

    http://login-id:password@UrlOfDomain.com/protectedPath/WebPage.html


Links:


Books:

"Apache Server Bible 2"
by Mohammed J. Kabir
ISBN # 0764548212, Hungry Minds

This book is very complete covering all aspects in detail. It is not your basic reprint of the apache.org documents like so many others.

Amazon.com
LDAP System Administration "LDAP System Administration",
Gerald Carter
ISBN 1565924916, O'Reilly & Associates

This book covers the use of OpenLDAP and the integration of services.

Amazon.com
NIS System Administration "Managing NFS and NIS",
by Hal Stern, Mike Eisler, Ricardo Labiaga
ISBN 1565925106, O'Reilly & Associates

Amazon.com

Return to http://YoLinux.com home page
Return to YoLinux Tutorial Index
Feedback Form

Copyright © 2000, 2001, 2005, 2006 by Greg Ippolito