0

I'm trying to implement PHP-LDAP authentication to authenticate and validate users. I'm using the following code. But, the password prompt doesn't appear if password is entered incorrect or domain name is not provided with username (in the form of username@domain or domain\username). It always shows "Authorization failed". If users provide correct username@domain and password they can log in. Code:

session_start();

if (strlen(@$_SERVER['PHP_AUTH_USER']) == 0 || strlen(@$_SERVER['PHP_AUTH_PW']) == 0) {
    header('WWW-Authenticate: Basic realm="test"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<h1>Authorization required</h1>';
    exit;
} else {
    $ldaprdn = $_SERVER['PHP_AUTH_USER'];
    $ldappass = $_SERVER['PHP_AUTH_PW'];
    $ldap_server = 'ldap_server_add';
    $ldapconn = ldap_connect("ldap_server_add") or die("Could not connect to ".$ldap_server." server.");
    $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);

    if ($ldapbind) {
        if (strrchr($_SERVER['PHP_AUTH_USER'], '@') || strrchr($_SERVER['PHP_AUTH_USER'], '\\')) {
            if (strrchr($_SERVER['PHP_AUTH_USER'], '@')) {
                $t = explode('@', $_SERVER['PHP_AUTH_USER']);
                $_SESSION['userid'] = $t[0];
            } else {
                $t = explode('\\', $_SERVER['PHP_AUTH_USER']);
                $_SESSION['userid'] = $t[1];
            }
        }
    } else {
        echo "<h1>Authorization failed</h1>";
    }
}

I cannot figure out the problem. Please help me.

4

1 に答える 1

0

簡単なトリックで解決策を得て、上記のコードを以下のように変更しました。

session_start();

function authenticate() {
    header('WWW-Authenticate: Basic realm="test"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<h1>Authorization required</h1>';
    exit;
}

if (strlen(@$_SERVER['PHP_AUTH_USER']) == 0 || strlen(@$_SERVER['PHP_AUTH_PW']) == 0) {
    authenticate();
} else {
    $ldaprdn = $_SERVER['PHP_AUTH_USER'];
    $ldappass = $_SERVER['PHP_AUTH_PW'];
    $ldap_server = 'ldap_server_add';
    $ldapconn = ldap_connect("ldap_server_add") or die("Could not connect to ".$ldap_server." server.");
    $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);

    if ($ldapbind) {
        if (strrchr($_SERVER['PHP_AUTH_USER'], '@') || strrchr($_SERVER['PHP_AUTH_USER'], '\\')) {
            if (strrchr($_SERVER['PHP_AUTH_USER'], '@')) {
                $t = explode('@', $_SERVER['PHP_AUTH_USER']);
                $_SESSION['userid'] = $t[0];
            } else {
                $t = explode('\\', $_SERVER['PHP_AUTH_USER']);
                $_SESSION['userid'] = $t[1];
            }
        }
    } else {
        authenticate();
    }
}
于 2012-07-25T05:27:26.007 に答える