PHP_AUTH_USER和LDAP

时间:2012-06-01 16:05:15

标签: php authentication header active-directory ldap

我正在尝试通过LDAP与Active Directory对PHP webapp的用户进行身份验证。

<?php
    $ldapconfig['host'] = 'ldapserv.xx.uni.edu';
    $ldapconfig['port'] = 389;
    $ldapconfig['basedn'] = 'dc=xx, dc=uni, dc=edu';
    $ldapconfig['authrealm'] = 'Secure Area';

    function ldap_authenticate() {
        global $ldapconfig;
        global $PHP_AUTH_USER;
        global $PHP_AUTH_PW;

        if ($PHP_AUTH_USER != "" && $PHP_AUTH_PW != "") {       
            $ds=@ldap_connect($ldapconfig['host'],$ldapconfig['port']) or exit ("Error connecting to LDAP server.");

            //Settings for AD
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);

            $r = @ldap_search( $ds, $ldapconfig['basedn'], 'uid=' . $PHP_AUTH_USER);
            if ($r) {
                $result = @ldap_get_entries( $ds, $r);
                if ($result[0]) {
                    if (@ldap_bind( $ds, 'uni\\' . $PHP_AUTH_USER, $PHP_AUTH_PW) ) {

                        return $result[0];
                    }
                }
            }
        }
        header('WWW-Authenticate: Basic realm="'.$ldapconfig['authrealm'].'"');
        header('HTTP/1.0 401 Unauthorized');
        return NULL;
    }

    if (($result = ldap_authenticate()) == NULL) {
        echo('Authorization Failed <br />');
        exit(0);
    }
    echo('Authorization success');
    print_r($result);

?>

此代码仅提示用户输入用户名/密码,除非他们单击取消。我做错了什么?

2 个答案:

答案 0 :(得分:1)

默认情况下,最近的PHP版本不再提供$ PHP_AUTH_USER和$ PHP_AUTH_PW变量,因此您的脚本甚至不会进入LDAP检查。删除最后两个“全局”行,并用$ _SERVER ['PHP_AUTH_USER']和$ _SERVER ['PHP_AUTH_PW']替换这些变量。

如果这没有用,请删除@字符以查看是否有错误。

答案 1 :(得分:0)

我能够使用session_register(以及更简单的代码)使用身份验证登录

<?php

if (isset($_POST['submitted'])) { 

    $username =$_POST['username'];
    $password=$_POST['password'];

    $ldap = ldap_connect("ldapserv.xx.uni.edu", 389) or exit ("Error connecting to LDAP server.");

    //Settings for AD
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);


    if($bind = ldap_bind($ldap, 'uni\\'.$username, $password)) {
        //Log them in!
        session_register("username");
        session_register("password");
        header("Location: https://" . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, -9) . "index.php" );
        exit;

    } else {

        echo('Invalid username or password.<br /><br />');
    }
}
?>
相关问题