Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Http Authentication
<?php
/**
* Attempt to wrap Http Authentication into a separate class...
*
* Ideas and some code from FuelPHP Controller_Rest
* https://github.com/fuel/fuel/blob/develop/fuel/core/classes/controller/rest.php
*
*/
class Cambiata_HttpAuth {
// BASIC SECURITY FUNCTIONS ---------------------------------------------------------
static public function basic_http_auth($callback_class, $callback_method)
{
$username = NULL;
$password = NULL;
if (isset($_SERVER['PHP_AUTH_USER']))
{ //Apache mod_php...
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
}
elseif (isset($_SERVER['HTTP_AUTHENTICATION']))
{ // Other servers...
if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']), 'basic') === 0)
{
list($username, $password) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHENTICATION'], 6)));
}
}
// check login result from callback function...
$login_check = call_user_func(array($callback_class, $callback_method), $username, $password);
// if not, use browser dialog
if (!$login_check) self::http_auth_login_dialog();
}
const X_AUTH_TOKEN = "HTTP_X_AUTH_TOKEN";
static public function header_token_auth($callback_class, $callback_method, $token_header_tag)
{
// If token header isn't set, return false
if (!isset($_SERVER[$token_header_tag])) self::login_fail();
// Get the token
$token = $_SERVER[$token_header_tag];
// Check if token is valid from callback function...
$login_check = call_user_func(array($callback_class, $callback_method), $token);
if (!$login_check) self::login_fail();
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//------------------------------------------------------------------------
static private function http_auth_login_dialog()
{
header('WWW-Authenticate: Basic realm="REST API"');
self::login_fail();
}
static private function login_fail()
{
header('HTTP/1.0 401 Unauthorized');
header('HTTP/1.1 401 Unauthorized');
exit('Not authorized.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment