Tuesday, March 5, 2013

PHP basic authentication

In one of my previous post I gave an example how to use the python httplib to create a request to a resource that requires basic authentication. Below I will illustrate how the basic authentication can be requested from server side with php.

To request basic authentication from the user, the server should set the '401 Unauthorized' header and also should set and send the 'WWW-Authenticate: Basic realm="e.g. Server name"' header. This can be done in php:

<?php
// send WWW-Authenticate header to the browser
header('WWW-Authenticate: Basic realm="Private server"');
header('HTTP/1.0 401 Unauthorized');
?>

After receiving the above headers the browser will pop up an window and will request the user to enter a username and password. If user enters the requested data and presses OK the data is sent to the server, in php you can check if the credentials are provided by inspecting the $_SERVER['PHP_AUTH_USER'] variable. The full source code of the example is below:

<?php

// check if the user entered the credentials
$authenticated = isset($_SERVER['PHP_AUTH_USER']);

if (!$authenticated) {
 request_authorization();
} else {
 
 // get username and password
 $username = $_SERVER['PHP_AUTH_USER'];
 $password = $_SERVER['PHP_AUTH_PW'];
 
 // check username and password
 if (check_credentials($username, $password)) {
  // authentication success
  echo "

Private zone

"; echo "

Hello {$username}.

"; echo "

Super secret content here :)

"; } else { // authentication failed, re-request the credentials request_authorization(); } } function request_authorization() { // send WWW-Authenticate header to the browser header('WWW-Authenticate: Basic realm="Private server"'); header('HTTP/1.0 401 Unauthorized'); // at this point the browser will request the credentials from the user // sends this only if the user presses the cancel button in the authentication pop up window echo "Private zone, authorized access only"; } // will check if $username and $password exists in the $users array function check_credentials($username, $password) { // array of users (e.g. fetched from a database) $users = array( "john" => "smith", "admin" => "supersecretpassword" ); if (array_key_exists($username, $users)) { if ($users[$username] === $password) { return true; } } return false; } ?>

Opening the page will result in this pop up window:

Wrong credentials:

Correct credentials:

Happy coding.

No comments: