20.3 User Authentication with Apache and PHP


Have you ever thought about authentication? Just think of an application consisting of dozens of screens every user should have certain permissions and certain rights. Therefore authentication is necessary. Apache and PHP provide various methods of user authentication. In this section you will take a closer look at the most important methods for authentication. You will be guided through the principles and learn how to build a secure site.

20.3.1 Apache

The easiest way to protect your site against users who are not allowed to visit it is to use Apache's basic authentication. Basic authentication can be used easily and it provides rudimentary security for your Web site.

The next example shows a short piece of an Apache configuration file:

 <Directory "/var/www/html">         <Files *>                 AuthType        Basic                 AuthName        Intranet                 AuthUserFile    /etc/httpd/conf/userfile                 require valid-user         </Files>     Options Indexes FollowSymLinks     AllowOverride None     Order allow,deny     Allow from all </Directory> 

As you can see, a so-called container is defined. The entire container defines attributes of the /var/www/html directory. Inside the block, a block called Files can be found. It is valid for all files in the directory and tells Apache to use basic authentication. As you can see, the type of authentication is set to Basic and a file containing the passwords is defined. A valid password is required to access the site.

After the block used for defining the type of authentication, some other options are defined. These options are not that important and won't be discussed in detail.

Figure 20.1 shows what happens when a user wants to access a site where authentication is needed.

Figure 20.1. Basic authentication.

graphics/20fig01.jpg

To administer the file containing the passwords, you can use a program called htpasswd. With the help of this program, you can add users, create new files, or change the password of a user. Let's take a look at the syntax overview of the command:

 [root@duron root]# htpasswd Usage:         htpasswd [-cmdps] passwordfile username         htpasswd -b[cmdps] passwordfile username password         htpasswd -n[mdps] username         htpasswd -nb[mdps] username password  -c  Create a new file.  -n  Don't update file; display results on stdout.  -m  Force MD5 encryption of the password.  -d  Force CRYPT encryption of the password (default).  -p  Do not encrypt the password (plaintext).  -s  Force SHA encryption of the password.  -b  Use the password from the command line rather than prompting for it. On Windows, TPF and NetWare systems the '-m' flag is used by default. On all other systems, the '-p' flag will probably not work. You have new mail in /var/spool/mail/root 

If you want to remove a user from the password file, just call the one and only Unix editor available, Vi(m), and remove the line corresponding to a user.

If you have to build business-critical applications, it can be helpful to use secure HTTP. In contrast to HTTP, secure HTTP is an encrypted protocol. It can be used in combination with Apache and helps you to protect yourself against sniffers. Sniffing means that somebody "listens" to the data you are transmitting across a network. Because of encryption, this is not possible. Apache's SSL extensions are based on a so-called public-private key encryption algorithm (RSA). To read a message, you need a private key matching the transmission. In addition, a public key is available. If data is sent to a client, the server encrypts the data using his private and his public key. The client gets the encrypted message and decodes the message using his keys. If somebody listens to the connection, he won't be able to decode the message if he doesn't have the correct keys. Mathematically it is possible to decode the key by trying all possible keys, but there are so many possibilities that it would take millions of years to find the correct key. The algorithm used by SSL can be considered to be secure.

Apache is one of the most flexible pieces of software available. It offers tremendous power, and it is an easy task to add features to the Web server. For the purpose of securing your Web sites, Apache offers the right tools for you. Because Apache can be considered to be stable, it is a secure packet.

20.3.2 PHP

In this section you will learn about securing an application built with PHP.

In the preceding section you saw what you can do with Apache. However, sometimes you don't have the ability to change the configuration of the Web server. In addition, Apache stores the list of users and passwords in a text file. With a huge number of users, this is not very efficient. Reading an entire file can be compared to a sequential scan, which is quite slow. To get around the problem, you can use a PostgreSQL database in combination with PHP authentication to do the job. In addition to performance, it will help you to gain a lot of flexibility because modifying a database is much easier than working with flat files and htpasswd.

Before you see how to implement a database-driven authentication system, it is time to take a look at how authentication can be used in PHP. Take a look at the following script:

 <?php         if      (!isset($PHP_AUTH_USER))         {                 Header("WWW-Authenticate: Basic realm=\"A Realm\"");                 Header("HTTP/1.0 401 Unauthorized");                 echo "No login\n";                 exit;         }         else         {                 echo "User: $PHP_AUTH_USER<br>";                 echo "Password: $PHP_AUTH_PW<br>";         } ?> 

$PHP_AUTH_USER is a predefined variable. If it is not defined, a window is displayed. In Figure 20.2 you can see what this window looks like when running Mozilla.

Figure 20.2. Authentication with PHP.

graphics/20fig02.jpg

After you have passed the authentication window, the data you have passed to the screen will be displayed:

 User: xy Password: mypasswd 

One important thing when dealing with authentication is that there is no way to influence the behavior of your scripts by passing parameters to the script via a URL.

Now take a look at the next listing:

http://localhost/auth/auth.php?PHP_AUTH_USER=John

Even when defining PHP_AUTH_USER, the output of the program will be the same. This is an important issue because otherwise it would be an easy task to fake a user.

Now that you have seen how to use authentication in combination with PHP, it is time to look at an example where we will use a PostgreSQL database for storing user information. Let's create a table and insert some values into the database first:

 CREATE TABLE authentication (         id serial,         name text,         passwd text ); INSERT INTO authentication (name, passwd) VALUES ('Hans', 'hello'); INSERT INTO authentication (name, passwd) VALUES ('Epi', 'Christina'); INSERT INTO authentication (name, passwd) VALUES ('Shelley', 'Alex007'); 

The following piece of code shows how a simple system can be built:

 <?php         if      (!isset($PHP_AUTH_USER))         {                 authenticate();         }         else         {                 if      (checkuser(dbconnect(), $PHP_AUTH_USER, $PHP_AUTH_PW))                 {                         echo "authentication successful";                 }                 else                 {                         echo "authentication failed<br>";                 }         }         function authenticate()         {                 header("WWW-Authenticate: Basic realm=\"Authentication\"");                 header( "HTTP/1.0 401 Unauthorized");         }         # connect to database ...         function dbconnect()         {                 $dbh = pg_connect("dbname=phpbook user=hs")                         or die ("cannot connect to database<br>");                 return $dbh;         }         # check if the user is valid ...         function checkuser($dbh, $user, $pwd)         {                 $sql = "SELECT COUNT(*) FROM authentication                         WHERE name='$user' AND passwd='$pwd'";                 $ret = pg_exec($dbh, $sql);                 $line = pg_fetch_row($ret, 0);                 if      ($line[0] > 0)                 {                         return true;                 }                 else                 {                         return false;                 }         } ?> 

If $PHP_AUTH_USER is not defined, the function called authenticate is started. It displays the authentication windows and quits. If the user has already logged in, checkuser is called. This function is responsible for finding out if the user is correct and if user and password are in the database. The first parameter passed to the function is a database handle, which is created by the dbconnect function. The dbconnect function is responsible for connecting to the database and returns a database handle. The second and third parameter contain the username and the password the user used for connecting to your Web site.

Let's take a look at the implementation of checkuser. First a SQL command is compiled. If there are more than zero users in the database, the user and the password are valid. The return value of checkuser will be analyzed and a string is displayed on screen.

When working with PHP authentication, you should take into consideration that authentication does not work when PHP is executed using the CGI interface. It works with mod_php but not with CGI.



PHP and PostgreSQL. Advanced Web Programming2002
PHP and PostgreSQL. Advanced Web Programming2002
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 201

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net