0
votes

I need to use realm authentication on a folder on a PHP site running on a Windows IIS 7.5 web server. I have the following code below that works great on any .php file within that directory.

The problem is I need to password protect access to the entire directory, including PDF, image files, css files etc. I can't place PHP code on those types of files.

I did have the IIS rewrite module installed on the server so I am assuming I can somehow add a rewrite in my web.config that can force all files through some sort of pass-through/handler PHP file.

I just have no idea how to do this.

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Jonas Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'User pressed Cancel';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as you password.</p>";
}
?>
1

1 Answers

1
votes

I have replied to a similar question and the difference is that you are using ISS and not Apache and you want to serve all files and not just a few types.

Here is a full web.config or you can just copy the <rule> tag. This rule will match all files except those with php extension (please not negate=true). You will have to change it to your specific requirements.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <directoryBrowse enabled="false" />
    <rewrite>
      <rules>
            <rule name="Authentication" stopProcessing="false">
                <match url="^(.*)$" negate="false" />
                <action type="Rewrite" url="validate.php?path={R:0}" appendQueryString="true" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" />
                    <add input="{QUERY_STRING}" pattern="^(.*\.php)$" negate="true" />
                </conditions>
            </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

And here is a different version of the isAuthenticated.php file that I used and using a bit of the code you posted.

$blacklistExtensions = array();

$path = $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.$_REQUEST["path"];
$pathInfo = pathinfo($path);

if(in_array($pathInfo["extension"], $blacklistExtensions)) {
    header("HTTP/1.1 403 Forbidden");
    exit;
}

if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Jonas Realm"');
    header('HTTP/1.0 401 Unauthorized');
    exit;
}

if(!file_exists($path)) {
    header("HTTP/1.1 404 Not Found");
    exit;
}

// Display the file and set the correct mimetype
$resource = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($resource, $path);
finfo_close($resource);

header("Content-Type: ".$mimetype);
readfile($path);

Hope this can get you started into finding a solution to this issue :)