Home > Articles > Programming

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Using HTTP-Auth for Password Protection in Scripted Applications

Many script programmers use some of the HTTP-Auth mechanism I’ve just described to prompt for login information for their applications. Essentially, their script—not the web server—sends a 401 code to the client, causing the dialog box to open for user input. The script then compares the information input to a user database to determine whether it constitutes a successful login to the application.

For example, consider the PHP code in Listing 1. When this code is placed on a server and accessed via a browser, the user gets the authentication pop-up. The credentials entered into the dialog box will be placed in the PHP $_SERVER variable so the script can check it against any appropriate resource.

Listing 1 HTTPAuth.php.

<?php

 // Check for credentials embedded in the request
 if (!isset($_SERVER[’PHP_AUTH_USER’])) {

 // User credentials have not been supplied with request
 // Send a 401 Unauthorized code to prompt for them
 header(’WWW-Authenticate: Basic realm="Realm Name"’);
 header(’HTTP/1.0 401 Unauthorized’);
 print "<p>The user clicked Cancel.</p>";
 exit;

 } else {

 // User credentials have been supplied with request

 // This will simply output the credentials. Typical apps
 // will check the credentials against a local user
 // database for validity and proceed accordingly
 print "<p>Username: {$_SERVER[’PHP_AUTH_USER’]}</p>";
 print "<p>Password: {$_SERVER[’PHP_AUTH_PW’]}</p>";
 }

?>

The script in Listing 1 simply outputs the information the user entered into the authentication dialog box. Actual application scripts would be far more complex, usually comparing the information in the $_SERVER variables against a user database to test their validity.

  • + Share This
  • 🔖 Save To Your Account