简体   繁体   English

带有TLS的PHP以实现安全的LDAP

[英]PHP with TLS for secure LDAP

I am trying to use remote LDAP server. 我正在尝试使用远程LDAP服务器。 For the purpose of security, I am trying to use only secure connection. 为了安全起见,我尝试仅使用安全连接。 I am able to get some code working but I am not sure, given the PHP documentation of start TLS itself, that if the following code works only on secure channel. 我能够使一些代码正常工作,但是鉴于启动TLS本身的PHP文档,我不确定如果以下代码仅在安全通道上有效。 Can anyone help with this please? 有人可以帮忙吗?

$is_valid_user = FALSE;

try {
    $ds = ldap_connect('ldap.foo.com', 389);
    if (! ldap_set_option($ds, LDAP_OPT_REFERRALS, 0)) {
        return "";
    }

    if (! ldap_start_tls($ds)) {
        return "";
    }
} catch(Exception $e) {
    return "";
}

if (! ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    $error = "LDAP Server protocol error.";
    return "";
}

try {
    $bnd = @ldap_bind($ds, 'uid='.$user.', ou=people, dc=ldap, dc=foo, dc=com' , $passwd);

    if ($bnd) {
        $is_valid_user = TRUE;

        $srch=ldap_search($ds, 'dc=ldap, dc=foo, dc=com', "uid=$user");
        $info=ldap_get_entries($ds, $srch);
        $userdn=$info[0]["dn"];
        $usernm=$info[0]["cn"][0];

        return $usernm;
    } else {
        return "";
    }
} catch(Exception $e) {
    return "";
}

Just a few general improvements below. 以下是一些常规改进。 And yes, how that's written it will not continue unless the connection is encrypted via TLS. 是的,除非通过TLS加密连接,否则它将不会继续下去。 The LDAP module doesn't throw any exceptions at the moment, so the try/catch block is not really needed. LDAP模块目前不会引发任何异常,因此真正不需要try / catch块。 Hard to tell without seeing the rest of your code, but is there a reason you want to return an empty string instead of false or null or some sort of error message? 在看不到代码其余部分的情况下很难说出来,但是是否有理由要返回空字符串而不是falsenull或某种错误消息?

$is_valid_user = false;

$ds = ldap_connect('ldap.foo.com', 389);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

if (!@ldap_start_tls($ds)) {
    return "";
}

$bindUser = 'uid='.ldap_escape($user, null, LDAP_ESCAPE_DN).',ou=people,dc=ldap,dc=foo,dc=com';
if (@ldap_bind($ds, $bindUser , $passwd)) {
    $is_valid_user = true;

    $srch = ldap_search($ds, $bindUser, '(objectClass=*)', ['cn']);
    $info = ldap_get_entries($ds, $srch);
    $userdn = $info[0]["dn"];
    $usernm = $info[0]["cn"][0];

    return $usernm;
} else {
    return "";
}

There are also several LDAP libraries available that make LDAP much easier with PHP. 还有一些可用的LDAP库,这些库使使用PHP的LDAP更加容易。 I would recommend LdapTools or adldap2 . 我建议使用LdapToolsadldap2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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