Question

I am using PHP to implement HTTP Basic Authentication on the Apache HTTP Server (version 2.2). The only directory I want to password-protect is a sub-directory of the main public web root of my website (for example purposes, let's call the protected directory '/private', and its realm "Private”).

If possible, I want users that have already been authenticated in the “Private” realm – and those users only – to see customised content on the web site’s home page (and any other web page, for that matter).

What I want to know is, is it possible to do this without forcing a login prompt at the top-level of my domain's top-level (e.g. www.jdclark.org or, for that matter, any other URIs outside if the “Private” realm)?

EDIT:

One technique that I have thought about applying to achieve the above is as follows: When a user has been authenticated into the “Private” realm via the access control in the ’/private’ directory, a session cookie could be set in PHP. I could then check for the presence of this cookie (which could possibility contain a session ID or some kind of unique random string), but although I’m don’t proclaim to be an IT security expert, this method feels a bit “hackish,” and something tells me that this is insecure (e.g. would it be trivial for a malicious user to spoof that cookie with an HTTP header?). Any advice would be very much appreciated.

Was it helpful?

Solution

Check for the presence of the HTTP authentication headers and use this to determine what to display.

if (isset($_SERVER['PHP_AUTH_USER'])) {
    $username = $_SERVER['PHP_AUTH_USER'];
    $password = $_SERVER['PHP_AUTH_PW'];
    // validate login credentials
    $private = true; // or false if validation fails
}

if ($private) {
    // load special view
}
else {
   // load normal view
}

This will not prompt the user to log in if they have not already done so elsewhere.

If you are going to be doing this in multiple places it would make sense to have a single re-usable class or file that provided a function to check for the headers and validate the credentials (returning true on success, false on fail) rather than duplicating code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top