Basic HTTP Authentication

Basic HTTP authentication uses a challenge/response scheme to authenticate users. The process begins when the user requests a file from a Web server. If the file is within a protected area, the server responds with a 401 (Unauthorized User) error, and the browser displays the familiar username/password dialog box. The user then enters a username and password and clicks on OK, which sends the information to the server for authentication. If the username and password pair is valid, the server displays the requested file. Otherwise, the dialog box appears and prompts the user to try again.

To use basic HTTP authentication, you must have available two elements: an authentication-enabled Web server and a list of usernames and passwords. However, authentication configuration varies from one Web server to the next. While Microsoft IIS has a graphical user interface for creating and administering a username and password list, the Apache Web server uses the "old school" method that requires a user to manually modify the server configuration and password files.

The next section will show you how to use basic HTTP authentication with Apache. For information on configuring basic HTTP authentication with Microsoft IIS, consult your server documentation, and ensure that you have installed all updates and service packs before starting the process.

Configuring HTTP Authentication on Apache

The first step in configuring basic HTTP authentication on Apache is to create the file containing usernames and passwords. This file contains a list of all valid users for a particular protected area (or realm), along with the matching password for each user. You can place this file anywhere on your Web server, preferably in a private directory above the document root. If your password file is kept under the document root, anyone with Web access can access your password file via a URL. For example, if your file is called passwordfile and it is located directly in the document root directory, its URL would be Obviously, this is not a good idea.

Creating the Users and Groups Files

Use the htpasswd program included in the Apache distribution (in the bin directory) to create the username/password file. To create a username/password file called users with an entry for the user jane, issue the following command:

  1. Type /usr/local/bin/apache/bin/htpasswd -c /usr/local/apache/users jane. The -c flag alerts the program that the file /usr/local/apache/users must be created.

  2. You are prompted to add a password for user jane. Enter the password and press Enter.

  3. You are prompted to confirm the password. Type the password again, exactly as before, and press Enter.

Open the /usr/local/apache/users file to see the username you just entered, followed by a colon, followed by the encrypted version of the password you just entered. For example:


To add additional users, such as joe, bob, and mary, follow the preceding steps, omitting the -c flag because the /usr/local/apache/users file already exists.

Categorizing your users into groups makes your life much easier, because you'll be able to grant access rights to an entire group rather than to 10 or 12 (or 200!) individual users. By granting access to an entire group, you won't have to manually list each individual member of that group in the corresponding access file.

To create a group file, manually create the file /usr/local/apache/groups. To define the friends group, which contains the users jane, joe, bob, and mary (who are already defined in your users file), type the following in the /usr/local/apache/groups file:

 friends: jane joe bob mary 

In the next section, you'll learn to configure Apache to allow members of the friends group to access a protected directory.

Configuring the Web Server

Configuration directives can be inserted either in the Apache httpd.conf file (found in /usr/local/apache/conf/) or in a separate .htaccess file, placed in the protected directory. For example:

  • To protect using an .htaccess file, place the file in /usr/local/apache/htdocs/privatestuff/.

  • To protect using httpd.conf, create a section in httpd.conf beginning with <Directory /usr/local/apache/htdocs/privatestuff/> and ending with </Directory>. The directives will go between these start and end tags, as you'll soon see.

One drawback to using multiple .htaccess files is that you must keep track of all of them! When issuing directives in the httpd.conf file, all of the directives are in one place and are easier to maintain. Whether you put the directives in an .htaccess file or within a <Directory> </Directory> section of the httpd.conf file, the information is the same.

  • AuthName. The name of the protected area, or realm, such as "My Private Stuff" or "Jane's Development Area."

  • AuthType. The authentication protocol in use, usually basic. Digest authentication also exists, in which the usernames and passwords are encrypted as they pass between browser and server. Digest authentication is unsupported by some older browsers, limiting its use in applications.

  • AuthUserFile. The full path to the file containing the usernames and passwords.

  • AuthGroupFile. The full path to the file containing the list of groups, if any.

  • require. Specifies which users and/or groups have access to the protected area. Can be valid users, just jane, just the friends group, or a combination.

A sample set of directives might look like this:

 AuthName "My Private Stuff" AuthType Basic AuthGroup /usr/local/apache/groups require group friends 

In this example, anyone accessing the privatestuff directory will be met with the username/password dialog box. If the user is a member of the friends group and enters the correct username and password, the protected information is displayed.

However, imagine the amount of server processing that is necessary for a Web site that has more visitors than just your friends. As your user base increases and Web server performance begins to erode, consider moving the usernames and passwords to a separate database table (which can be parsed by the Web server faster than a simple text file) and creating your own authentication systems.

Working with PHP Authentication Variables

A custom PHP script can mimic the HTTP authentication challenge/response system by setting HTTP headers that cause the automatic display of the username/password dialog box. PHP stores the information entered in the dialog box in twp variables ($_SERVER[PHP_AUTH_USER] and $_SERVER[PHP_AUTH_PW]) that can be used to validate input.

To become familiar with sending authorization headers via the header() function, first create a PHP script that pops up the username/password dialog box without validating a username/password pair.

The following script (call it authorizel.php) checks for the existence of a value for $_SERVER[PHP_AUTH_USER] , displays the username/password dialog box if a value does not exist, and then exits:

 <?php // Check to see if $_SERVER[PHP_AUTH_USER] already contains info if (!isset($_SERVER[PHP_AUTH_USER])) {           // If empty, send header causing dialog box to appear           header('WWW-Authenticate: Basic realm="My Private Stuff"');           header('HTTP/1.0 401 Unauthorized');           echo 'Authorization Required.';           exit; } else {           // If not empty, display values for variables           echo "<P>You have entered this username: $_SERVER[PHP_AUTH_USER]<br>";           echo "You have entered this password: $_SERVER[PHP_AUTH_PW]</p>"; } ?> 

In this case, if any value exists, the script assumes that the username and password are valid and returns the value of the three PHP authorization variables as directed in the else statement. Absolutely no authentication is performed in this example, because the script does not check the values against a master list of allowable users.

The header() function is key to this script; the HTTP header is the first output from the script to the browser. When a user enters a username and password in the dialog box and clicks on OK, the page reloads and sends another HTTP header to the server, this time with the variables populated.

Since $_SERVER[PHP_AUTH_USER] now contains a value, the if statement returns false and the script skips to the else statement, which contains code to print the variable information to the screen.

Now that you know how to create the dialog box, write some code that validates these values. The easiest method is to hard-code acceptable values in the script, as shown in the following script (call it authorize2.php):

 <?php // Check to see if $_SERVER[PHP_AUTH_USER] already contains info if (!isset($_SERVER[PHP_AUTH_USER])) (           // If empty, send header causing dialog box to appear           header('WWW-Authenticate: Basic realm="My Private Stuff"');           header('HTTP/1.0 401 Unauthorized');           echo 'Authorization Required.';           exit; } else {           // If not empty, do something else           // Try to validate against hard-coded values           if (($_SERVER[PHP_AUTH_USER] == "jane") && ($_SERVER[PHP_AUTH_PW] == "mypassword")) {                   echo "<P>Since you have entered a username of $_SERVER[PHP_AUTH_USER] and a password of $_SERVER[PHP_AUTH_PW], you are authorized to be here!</P>";           } else {                   echo "You are not authorized!";              } ) ?> 

But who wants to hard-code all valid usernames and passwords into their authentication script? It's an awful lot of work. Furthermore, if you carry your authentication routine through numerous pages, each of those pages must contain the entire list. If you have to make a change in the list, you have to make it on every single page containing the list. It's better to carry through only an authorization routine, which accesses a database containing all the usernames and passwords.

Not surprisingly, you'll learn about this method next!

PHP Essentials
PHP Essentials, 2nd Edition
ISBN: 1931841349
EAN: 2147483647
Year: 2002
Pages: 74 © 2008-2017.
If you may any questions please contact us: