Using HTTP Authentication with PHP
DiggBlinkRedditDeliciousTechnorati
article by Srirangan
This is an article which explains in simple words what HTTP Authentication is and how to make use of HTTP Authentication in your PHP driven website.
What is HTTP Authentication?
Certain group of pages -- usually refered to as a protected realm or just a realm -- would only be available to certain people who are able to provide credentials if challenged by the server. Such a method of authentication -- done by the HTTP (web) server -- is known as HTTP Authentication.
Steps involved in HTTP Authentication
1. HTTP client, e.g. a web browser, requests a page that is part of a protected realm. The server responds with a 401 Unauthorized status code and includes a WWW-Authenticate header field in its response. This header field will contain at least one authentication challenge applicable to the requested page.
2. The client makes another request, this time including an Authentication header field which contains the client's credentials applicable to the server's authentication challenge.
3. If the server accepts the credentials, it returns the requested page. Otherwise, it returns another 401 Unauthorized response to inform the client the authentication has failed.
HTTP Authentication and PHP
With PHP it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window.
Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays.
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version.
Basic HTTP Authentication
The basic authentication scheme assumes that your (the client's) credentials consist of a username and a password where the latter is a secret known only to you and the server.
The server's 401 response contains an authentication challenge consisting of the token "Basic" and a name-value pair specifying the name of the protected realm.
Here's an example of a PHP implementation of the Basic HTTP Authentication Scheme:
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
Digest Access Authentication
This is a more sophisticated procedure to securely prevent replay attacks,
First, the WWW-Authenticate header of the server's initial 401 response contains a few more name-value pairs beyond the realm string, including a value called a nonce. It is the server's responsibility to make sure that every 401 response comes with a unique, previously unused nonce value.
The Authentication header of your browsers follow-up request contains your clear-text username, the nonce value it just received, and the so-called digest-request, which it might compute as follows:
A1 = string.hashMD5 (username + ":" + realm + ":" + password)
A2 = string.hashMD5 (paramTable.method + ":" + paramTable.uri)
requestdigest = string.hashMD5 (A1 + ":" + nonce + ":" + A2)
Because these input values are either known to the server or are part of the request headers, it can do the same computation you did and if its computation yields the same request digest, it can be sure that you are in posession of the correct password.
This example shows you how to implement a simple Digest HTTP authentication script:
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
preg_match_all('@(w+)=(['"]?)([a-zA-Z0-9=./\_-]+)2@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
HTTP Authentication example forcing a new name/password
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource
";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
authenticate();
}
else {
echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
echo "Old: {$_REQUEST['OldAuth']}";
echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>
";
echo "<input type='hidden' name='SeenBefore' value='1' />
";
echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />
";
echo "<input type='submit' value='Re Authenticate' />
";
echo "</form></p>
";
}
?>
Security Considerations
You should keep in mind that even with digest authentication, all data except for your password is transmitted in plain view, fully accessible to potential eavesdroppers.
Also there's no way for the client to establish that it's actually talking to the server it intends to talk to. There's no mechanism in place that allows the server to authenticate itself to the client.
References
[1] HTTP Protocol
[2] PHP Documentation