0

我正在尝试实现 PHP-LDAP 身份验证来验证和验证用户。我正在使用以下代码。但是,如果输入的密码不正确或没有提供用户名的域名(以用户名@域或域\用户名的形式),则不会出现密码提示。它总是显示“授权失败”。如果用户提供正确的用户名@域和密码,他们可以登录。代码:

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>";
    }
}

我无法弄清楚问题所在。请帮我。

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 回答