Setup Authentication/Redirect mechanism in PHP

Wondering how to force users to authenticate with LDAP or any other source before they can access a web page? Here’s the defined flow how the system should ideally work:

1. User try to access a restricted page – Force redirect user to login page
2. User logs in – Authenticate against source (LDAP/DB). On success – redirect user to original page. On failure – show message and remain on login page
3. User hits the home page and passes authentication – Configure a HOME_PAGE so that users are redirected to home page if no reference url is identified.

The code comprises of the following components:
1. Login page – acclogin.php
2. Authentication class – Authenticate_internal.class
3. Configuration page – token_include_internal.php
4. Restricted page – create_token_internal.php

1. Restricted page

<?php
include_once "debugmode_internal.php";
include_once "token_include_internal.php";
include_once "Authenticate_internal.class";

if(!Authenticate::validateAuthCookie())
{
	try{
	//echo "Please login";
	//$pageDir = getPageDirectory();
	$pageUrl = getPageURL();
	header("Location: ".LOGIN_PAGE."?ref=$pageUrl");
	}
	catch(AuthException $e)
	{
		echo "Cookie could not be extended";
	}
}

//Your normal php/html stuff goes here. The top part takes care that the user is authenticated to access the page
?>

2. Config/Common Page

<?php

define ('LOGIN_PAGE', 'acclogin.php');
define ('HOME_PAGE', 'create_token_internal.php');

// --
// Function Name: getPageURL()
// Description: Returns the URL of the current page
// --
function getPageURL()
{
	$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
	if ($_SERVER["SERVER_PORT"] != "80")
	{
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} 
	else 
	{
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}

function getPageDirectory()
{
	$pageURL = getPageURL();
	$pageDir = implode("/", (explode('/', $pageURL, -1)));
	return $pageDir;
}
?>

3. Authentication class – Takes care of authenticating the user as well as issuing the token

<?php 

$cookiedomain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; 

define( 'COOKIE_DOMAIN', $cookiedomain ); 
define( 'COOKIE_PATH', '/' ); 
define( 'COOKIE_AUTH', 'login' ); 

define( 'SECRET_KEY', 'dk;l1894!851éds-fghjg4lui:è3afàzgq_f4fá.' ); 

define( 'USER_SUFFIX', '@yourdomain.com');
define( 'LDAP_SERVER', '192.168.111.22');

class Authenticate { 

	private $refUrl;

    public function __construct( $username, $password, $remember, $refUrl ) { 
     
        $this->authenticate( $username, $password, $remember, $refUrl ); 
         
    } 
     
    private function authenticate( $username, $password, $remember, $refUrl ) { 
         
    } 
     
    private function authenticate( $username, $password, $remember, $refUrl ) { 

		if(!self::validateAuthCookie())
		{
			$ldap = ldap_connect(LDAP_SERVER);
			if($bind = ldap_bind($ldap, $username.USER_SUFFIX, $password))
			{
				$this->setCookie( $username, $remember );
				echo "refUrl: ".$refUrl."
"; if(!empty($refUrl)) { //echo "refUrl Is Set
"; header("Location: ".$refUrl); } else { //echo "refUrl Is Not Set. Redirecting to".HOME_PAGE."
"; header("Location: ".HOME_PAGE); } } else { //echo "Login failed. Please try again.
"; throw new AuthException( "Invalid user credentials." ); } } else { echo "Welcome back $username
"; } } private function setCookie( $username, $remember = false ) { if ( $remember ) { $expiration = time() + 1209600; // 14 dagen } else { $expiration = time() + 600; // 2 mins } $cookie = $this->generateCookieData( $username, $expiration ); // -- // setcookie — Send a cookie // bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) // -- if ( !setcookie( COOKIE_AUTH, $cookie, $expiration, COOKIE_PATH, COOKIE_DOMAIN, false, true ) ) { throw new AuthException( "Could not set cookie." ); } } private function generateCookieData( $username, $expiration ) { $key = hash_hmac( 'md5', $username . $expiration, SECRET_KEY ); $hash = hash_hmac( 'md5', $username . $expiration, $key ); $cookie = $username . '|' . $expiration . '|' . $hash; return $cookie; } public static function logOut( ) { setcookie( COOKIE_AUTH, "", time() - 1209600, COOKIE_PATH, COOKIE_DOMAIN, false, true ); } public static function validateAuthCookie() { if ( empty($_COOKIE[COOKIE_AUTH]) ) return false; list( $id, $expiration, $hmac ) = explode( '|', $_COOKIE[COOKIE_AUTH] ); if ( $expiration < time() ) return false; $key = hash_hmac( 'md5', $id . $expiration, SECRET_KEY ); $hash = hash_hmac( 'md5', $id . $expiration, $key ); if ( $hmac != $hash ) return false; /* // -- If cookie is valid, extend the expiration time $cookie = self::generateCookieData( $username, $expiration + 120); echo ($expiration + 120); // -- // setcookie — Send a cookie // bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) // -- if ( !setcookie( COOKIE_AUTH, $cookie, $expiration + 120, COOKIE_PATH, COOKIE_DOMAIN, false, true ) ) { throw new AuthException( "Could not set cookie." ); } */ return true; } public static function getUserId() { list( $id, $expiration, $hmac ) = explode( '|', $_COOKIE[COOKIE_AUTH] ); return $id; } } class AuthException extends Exception {} ?>

4. Login page

<?php

include_once "Authenticate_internal.class";
include_once "license_include_internal.php";

/*
$pageURL = getPageURL();
echo $pageURL."
"; $pageDir = getPageDirectory(); echo $pageDir."
"; */ $refUrl = $_GET['ref']; //echo $refUrl; if(isset($_POST['submit'])) { try { $auth = new Authenticate($_POST['username'], $_POST['password'], false, $_POST['refurl']); } catch(AuthException $e) { echo "Invalid login. Please try again"; } //echo "Execute the code"; /* $suffix = '@yourdomain.com'; $ldap = ldap_connect("192.168.111.222"); if($bind = ldap_bind($ldap, $_POST['username'].$suffix, $_POST['password'])) { echo "Login successful
"; } else { echo "Login failed. Please try again.
"; } */ } /* if(Authenticate::validateAuthCookie()) { echo "Welcome back"; } else { echo "Please login"; } */ ?> function validate() { return true; } --HTML CONTENT-- LDAP Authentication
Username: @yourdomain.com
Password:
 
Advertisements
Posted in PHP

2 thoughts on “Setup Authentication/Redirect mechanism in PHP

  1. Hey there, You have done a great job. I will definitely digg
    it and personally suggest to my friends. I’m confident they’ll be benefited from
    this website.

  2. Having read this I believed it was very informative.

    I appreciate you spending some time and effort to put this short article together.
    I once again find myself spending way too much time both reading and leaving comments.
    But so what, it was still worthwhile!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s