简体   繁体   中英

Apache2, PHP: create automatic ntlm login page

I have Apache2 with PyAuthenNTLM2 module (see https://github.com/Legrandin/PyAuthenNTLM2 ). This Apache module put the windows user name in $_SERVER['REMOTE_USER'].

To enable this you need to put a directive similar to following in apache config (or htaccess) for a file or directory:

Order allow,deny
Allow from all

AuthType NTLM
AuthName "Test"
require valid-user

PythonAuthenHandler pyntlm
PythonOption Domain TESTDOMAIN
PythonOption PDC 192.168.0.10

The thing is that any files under such a directory (including css, js) are only accessible if the NTLM credential are supplied by browser. So using a include that is "ntlm protected" in a page that is not will not work.

Anyway what I want is a single page that sets up a session and further authorization is done using the session. if session is not set yet or expired the user is invisibly transferred to the automatic login page and then back to the actual requested page.

how can I achieve that?

I came up with following script / solution:

<?php

$validApplications = array("Application_1", "Application_2");
$baseUrl = 'http://' . $_SERVER["SERVER_NAME"] . '/';

if(!isset($_SERVER["REMOTE_USER"])){
    header('HTTP/1.1 401 Not Authorized', true, 401);
    //...display error page
    exit(0);
}

if(!isset($_GET["applicationName"]) 
        || !in_array($_GET["applicationName"], $validApplications) ){
    header('HTTP/1.1 400 Bad Request', true, 400);  
    //...display error page
    exit(0);
}

$application = $_GET["applicationName"];

if(!isset($_GET["returnTo"])){
    $returnTo = $baseUrl . $application . "index.php";
} else {
    $returnTo = $_GET["returnTo"];
}

$sessionName = "PHP" . $application . "Session";

session_name($sessionName);
session_start();

session_regenerate_id(TRUE);
/* erase data carried over from previous session */
$_SESSION=array();
$_SESSION['login'] = $_SERVER['REMOTE_USER'];
header("Location: " . $returnTo);
?>

This script, lets call it login.php must be under an according Apache2 module that can set $_SERVER["REMOTE_USER"] (I use PyAuthenNTLM2) like displayed in my Question.

Each web page in ana application then must first check if $_SESSION['login'] is set or not and if not redirect to this login page:

if (!isset($_SESSION['login'])) {
    $queryString = "returnTo=" . urlencode($_SERVER["REQUEST_URI"]) . "&applicationName=Application_1";
    header ("location: " . $baseUrl . "login.php?" . $queryString);
    exit(0);
}

I have done this with Apache and PHP, you'll need to look at session handling. A quick google for "python session handling" returned various examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM