25 Jun

HTTP Digest Authentication with PHP

The code for using HTTP Digest Authentication with PHP.


<?php
$realm = 'Restricted area';

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');
}

if (!empty($_SERVER['PHP_AUTH_DIGEST'])) {
	$data = parseHttpDigest($_SERVER['PHP_AUTH_DIGEST']);
	if(!$data) die('Wrong Credentials!');

	// generate the valid response
	$password = 'mypass';//$sql->getOne("SELECT password FROM User WHERE username=".$data['username']);
	$A1 = md5($data['username'] . ':' . $realm . ':' . $password);
	$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
	print 'Doors open, beds made - welcome home';
}

//Function to parse the http auth header
function parseHttpDigest($digest) {
	//Sample $_SERVER['PHP_AUTH_DIGEST']
	//username="admin", realm="Restricted area", nonce="467f579606f46", uri="/Projects/Nexty/Tests/auth.php", algorithm="MD5", qop="auth", cnonce="zaR5Of4nOsWwx9nA", nc=00000001, response="27212bf93d58fc12b5b7f5b0b95dc38b", opaque="cdce8a5c95a1427d74df7acbf41c9ce0"

    //Protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);

    $data = array();
    $parts = explode(", ", $digest);

    foreach ($parts as $element) {
		$bits = explode("=", $element);
		$data[$bits[0]] = str_replace('"','', $bits[1]);

		unset($needed_parts[$bits[0]]);
    }
    return $needed_parts ? false : $data;
}

Links