Вывод данных из ad php. Запрос данных из AD

  • 20.06.2020

Никогда не думал, что столкнусь с такой задачей, тем не в один прекрасный день возникла необходимость создать корпоративный портал для внутреннего использования. В организации есть домен и куча пользователей в этом домене. Было бы безусловно круто не плодить сущности (не создавать заново учетки для пользователей), а как-то привязаться к домену.

Сначала был долгий мозговой штурм и решали на чем делать этот портал - то ли вручную на PHP или ASP, то ли использовать какой-то готовый узкоспециализированный продукт и использовать его. При том, что этот продукт должен быть бесплатным. Естественно, никакого вменяемого бесплатного решения именно для корпоративного портала не нашлось, а писать все это вручную не было особого желания, возникла мысль - "а может Joomla?"

Сначала эту идею пытались закопать, ибо "не круто" но чем дальше обсуждали, тем больше чаша весов склонялась в пользу Joomla. Проверенного, распространенного и абсолютно бесплатного. Осталось решить только одно - как подружить Joomla с Active Directory. Оказалось, это возможно, хотя пришлось немного повозиться.

Я не буду расписывать такие простые истины, например, как установить Joomla на локальный хост и прочее, сразу к делу.

1 этап - правка файла PHP.ini

Нужно раскомментировать строчку:

extension=php_ldap.dll

Это библиотека, благодаря которой возможно взаимодействие Joomla с доменом Active Directory по протоколу LDAP.

2 этап - настройка плагина "Авторизация LDAP"

Идем в менеджер плагинов и ищем среди них "Авторизация LDAP", активируем его.

Предположим, что домен у нас называется domain.local, адрес контроллера домена - 192.168.0.1.

В настройках плагина нужно сделать следующие настройки (по крайней мере, у меня так заработало:)

Параметр Значение Комментарий
Хост 192.168.0.1 IP-адрес контроллера домена
Порт 389 не трогаем
Выполнять LDAP3 ДА
Выполнять TLS НЕТ
Следовать перенаправлениям НЕТ
Метод авторизации Привязать и найти При успешной авторизации Joomla создаст свою внутреннюю учетку, которую можно будет потом поместить в ту или иную группу доступа. К сожалению, группы пользователей из Active Directory Joomla подтягивать не умеет. Если нашли способ сделать это, поделитесь в комментариях к статье!
Базовый DN dc=domain,dc=local Разделяем домен на уровни и перед каждым уровнем пишем dc=..., между ними никаких пробелов, только запятые
Строка поиска sAMAccountName= Регистр имеет значение!
Пользовательский DN оставляем пустым
Имя пользователя подлючения Этот адрес электронной почты защищён от спам-ботов. У вас должен быть включен JavaScript для просмотра. Имя доменного администратора
Пароль подключения qwerty123 Соответственно, пароль доменного администратора
Map: Full Name displayName То, как на сайте будет высвечиваться имя пользователя
Map: Email mail то же самое - емэйл
Map: User ID uid идентификатор пользователя

Сохраняем настройки, открываем сайт и пытаемся залогиниться. При этом вводить имя доменного пользователя указываем без @domain.local - все должно заработать!

Подозреваю, что многие нюансы зависят от версий программного обеспечения. На всякий случай, все это тестировалось на следующем сервере:

  • Веб-сервер - Xampp 5.6.15 (PHP 5.6.15)
  • Joomla 3.6.3
  • Контроллер домена Windows Server 2008 R2

добавлено 26.10.2016

Замечена странность - Joomla не хочет авторизовать пользователей, чей логин в домене не совпадает с адресом электронной почты в Exchange. При попытке авторизации выдается сообщение об ошибке:

Предупреждение

У вас нет права доступа к закрытой части сайта.

Решение данной проблемы пока не найдено. Если вы знаете, как это преодолеть, пожалуйста, поделитесь в комментариях.

1

Я разрабатываю простой сайт в PHP, чтобы некоторые пользователи могли выполнять определенные задачи. Моя цель - получить авторизацию на основе роли для пользователей, и они должны видеть разные страницы в соответствии с их членством в группе LDAP. Это, как я пытаюсь реализовать IT-

1) use php-ldap library functions to connect to the LDAP server 2) extract the dn of the group name and username by ldapsearch from the user base dn and group base dn 3) search for the "memberOf" attributes in the user entry and match them with the group dn. Return true if matched 4) Search for the "member" attributes in the group entry and match them with the user dn. Return true if matched.

До сих пор я испытал это на сервер OpenLDAP и это, кажется, работает, но я хочу, чтобы сценарий работать с другими серверами каталогов, как ApacheDS, активное каталог и 389ds. Поскольку у меня нет доступа к нескольким серверам каталогов, я хочу сообщить, будут ли эти шаги работать на других серверах каталогов или нет. Любая помощь в этом отношении будет оценена по достоинству. Заранее спасибо.

0

Здесь находится фильтр «Мой пользовательский фильтр» (& (| (objectClass = person) (objectClass = inetOrgPerson)) (| (uid = {$ username}) (cn = {$ username}) (sAMAccountname = {$ username}))) "и фильтр группового поиска" (| (objectClass = groupOfNames) (objectClass = posixGroup)) " - Anindya Mukherjee 09 сен. 14 2014-09-09 14:37:05

  • 1 ответ
  • Сортировка:

    Активность

0

Эти шаги будут работать в основном на других LDAP-серверах. Вы должны будете иметь возможность изменять атрибуты, которые вы используете, хотя, как ActiveDirectory, например, использует атрибут samAccountName где LDAP-схема по умолчанию использует uid

Посмотрите на https://github.com/heiglandreas/kimai/blob/feature/fixLDAPAuthentication/core/libraries/Kimai/Auth/Ldapadvanced.php , которые могут содержать некоторые полезные фрагменты. Он не учитывает проблему, когда членство в группе определяется в usernode!

0

Спасибо за информацию. Мой фильтр поиска пользователей ищет атрибуты объектов inetOrgPerson или "person" и атрибуты "uid" или "cn" или "sAMAccountname", поэтому он должен работать для AD. Что касается AD, хранящего информацию о группе во входной записи пользователя, я изменил поток процесса, так что сначала пользовательская запись была проверена для информации о группе, а если return false, выполните поиск в группе в группе ou. Меня беспокоит то, что, если какой-либо другой сервер каталогов использует нестандартный способ и другой атрибут и/или класс объектов для хранения информации о группе. -

16 years ago

Try this script if you don"t know how to add an user in the AD Win2K.
To have more informations about the attributes, open the adsiedit console in the Support Tools for Win2K.

$adduserAD["cn"] =
$adduserAD["instancetype"] =
$adduserAD["objectclass"] = "top";
$adduserAD["objectclass"] = "person";
$adduserAD["objectclass"] = "organizationalPerson";
$adduserAD["objectclass"] = "user";
$adduserAD["displayname"] =
$adduserAD["name"] =
$adduserAD["givenname"] =
$adduserAD["sn"] =
$adduserAD["company"] =
$adduserAD["department"] =
$adduserAD["title"] =
$adduserAD["description"] =
$adduserAD["mail"] =
$adduserAD["initials"] =
$adduserAD["samaccountname"] =
$adduserAD["userprincipalname"] =
$adduserAD["profilepath"] =
$adduserAD["manager"] = ***Use DistinguishedName***

if (!($ldap = ldap_connect("localhost"))) {
die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, "[email protected]", $password))) {
die ("Could not bind to the LDAP account");
}
if (!(ldap_add($ldap, "CN=New User,OU=OU Users,DC=pc,DC=com", $adduserAD))){
echo "There is a problem to create the account
echo "Please contact your administrator !";
exit;
}
ldap_unbind($ldap);

12 years ago

Here is how to add a user with a hashed MD5 password to OpenLDAP. I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result. You cannot just base64 encode what is returned by PHP"s md5() or sha() hash functions, because they return a hexadecimal text string. First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password. You don"t have to use {MD5}, you could pick a different hash if that is what you have. The output from one of these hashed passwords will look like this: {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats: This technique will not work if you hashed the password using a salt value (but Drupal does not). This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

$ds = ldap_connect($serverAddress);
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
$r = ldap_bind($ds, $managerDN, $managerPassword);
$ldaprecord["cn"] = $newuser_username;
$ldaprecord["givenName"] = $newuser_firstname;
$ldaprecord["sn"] = $newuser_surname;
// put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
$ldaprecord["objectclass"] = "person";
$ldaprecord["objectclass"] = "organizationalPerson";
$ldaprecord["objectclass"] = "inetOrgPerson";
$ldaprecord["mail"] = $newuser_email_address;
$ldaprecord["telephoneNumber"] = $newuser_phone_number;
// and now the tricky part, base64 encode the binary hash result:
$ldaprecord["userPassword"] = "{MD5}" . base64_encode(pack("H*",$newuser_md5hashed_password));
// If you have the plain text password instead, you could use:
// $ldaprecord["userPassword"] = "{MD5}" . base64_encode(pack("H*",md5($newuser_plaintext_password)));
$r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }

11 years ago

I created a simple function that can be called to create global distribution groups in Active Directory:

function ldap_createGroup ($object_name , $dn , $members , $ldap_conn )
{
$addgroup_ad [ "cn" ]= " $object_name " ;
$addgroup_ad [ "objectClass" ][ 0 ] = "top" ;
$addgroup_ad [ "objectClass" ][ 1 ] = "group" ;
$addgroup_ad [ "groupType" ]= "2" ;
$addgroup_ad [ "member" ]= $members ;
$addgroup_ad [ "sAMAccountName" ] = $object_name ;

Ldap_add ($ldap_conn , $dn , $addgroup_ad );

If(ldap_error ($ldap_conn ) == "Success" )
return true ;
else
return false ;
}
?>

You can call this function using the follow code:

$ldap_conn = ldap_bind ();
$object_name = "Test Group" ;
$dn = "CN=" . $object_name . ",OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;
$members = "CN=User1,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;
$members = "CN=User2,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM" ;

Ldap_createGroup ($object_name , $dn , $members , $ldap_conn );
?>

The other function I created is ldap_bind(), and this can be used to bind to an LDAP server:

function ldap_bind ()
{
$ldap_addr = "192.168.1.1" ; // Change this to the IP address of the LDAP server
$ldap_conn = ldap_connect ($ldap_addr ) or die("Couldn"t connect!" );
ldap_set_option ($ldap_conn , LDAP_OPT_PROTOCOL_VERSION , 3 );
$ldap_rdn = "domain_name\\user_account" ;
$ldap_pass = "user_password" ;

// Authenticate the user against the domain controller
$flag_ldap = ldap_bind ($ldap_conn , $ldap_rdn , $ldap_pass );
return $ldap_conn ;
}
?>

13 years ago

When adding/editing attributes for a user, keep in mind that the "memberof" attribute is a special case. The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute "member":

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com" ;
$group_info [ "member" ] = $dn ; // User"s DN is added to group"s "member" array
ldap_mod_add ($connect , $group_name , $group_info );

?>

11 years ago

This solution works for us.
In the form the CN and pwdtxt are randomly generated from strict rules.
This script creates 50-60 users i AD pr.day! and never even had a glitch!

## From form
$CN = $_POST [ "CN" ];
$givenName = $_POST [ "givenName" ];
$SN = $_POST [ "SN" ];
$mail = $_POST [ "mail" ];
$Phone = $_POST [ "Phone" ];
$pwdtxt = $_POST [ "pwdtxt" ];

$AD_server = "localhost:390" ; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "[email protected]" ; //Administrative user
$AD_Auth_PWD = "duppiduppdupp" ; //The password

$dn = "CN=" . $CN . ",OU=Brukere,DC=student,DC=somwhere,DC=com" ;

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"" ;
$len = strlen ($newPassword );
$newPassw = "" ;

for($i = 0 ; $i < $len ; $i ++) {
$newPassw .= " { $newPassword { $i }} \000" ;
}

## CONNNECT TO AD
$ds = ldap_connect ($AD_server );
if ($ds ) {
ldap_set_option ($ds , LDAP_OPT_PROTOCOL_VERSION , 3 ); // IMPORTANT
$r = ldap_bind ($ds , $AD_Auth_User , $AD_Auth_PWD ); //BIND

$ldaprecord [ "cn" ] = $CN ;
$ldaprecord [ "givenName" ] = $givenName ;
$ldaprecord [ "sn" ] = $SN ;
$ldaprecord [ "objectclass" ][ 0 ] = "top" ;
$ldaprecord [ "objectclass" ][ 1 ] = "person" ;
$ldaprecord [ "objectclass" ][ 1 ] = "organizationalPerson" ;
$ldaprecord [ "objectclass" ][ 2 ] = "user" ;
$ldaprecord [ "mail" ] = $mail ;
$ldaprecord [ "telephoneNumber" ] = $Phone ;
$ldaprecord [ "unicodepwd" ] = $newPassw ;
$ldaprecord [ "sAMAccountName" ] = $CN ;
$ldaprecord [ "UserAccountControl" ] = "512" ;
//This is to prevent the user from beeing disabled. -->
http : //support.microsoft.com/default.aspx?scid=kb;en-us;305144

$r = ldap_add ($ds , $dn , $ldaprecord );

} else {
echo "cannot connect to LDAP server at $AD_server ." ;
}

?>

This is code example creates a user i AD.
We use this on an internal web page to create
temporary users that kan access the wireless network.
We have a .pl script that deletes the users after 24H.

11 years ago

Once i"am having problmes to add attributes with boolean syntax (1.3.6.1.4.1.1466.115.121.1.7)

$["boolean_attr"]=true; //give me one warning, ldap_add(): Add: Invalid syntax

solved this by setting the value on this:

$["boolean_attr"]="TRUE";

hope this can helps.

16 years ago

In response to jharnett"s question about accounts disabled by default from ldap_add, we have found a solution.

The attribute userAccountControl contains a value that includes whether the account is disabled or enabled. The default for us is 546; when we changed that to 544 the account became enabled. Changing whatever value is in userAccountControl by 2 seems to enable or disable the account.

The following code worked for us to create a new user with an enabled account:

$adduserAD["userAccountControl"] = "544";

We just added this element to the above example"s array.

7 months ago

Create Group in Active Directory

$ds = ldap_connect ("IP-server/localhost" );
$base_dn = "CN=Group name,OU=Organization Unit,DC=Domain-name,DC=com" ; //distinguishedName of group

If ($ds ) {
// bind with appropriate dn to give update access
ldap_bind ($ds , , "some-password" );

//Add members in group
$member_array = array();
$member_array [ 0 ] = "CN=Administrator,OU=Organization Unit,DC=Domain-name,DC=com" ;
$member_array [ 1 ] = "CN=User,OU=Organization Unit,DC=Domain-name,DC=com" ;

$entry [ "cn" ] = "GroupTest" ;
$entry [ "samaccountname" ] = "GroupTest" ;
$entry [ "objectClass" ] = "Group" ;
$entry [ "description" ] = "Group Test!!" ;
$entry [ "member" ] = $member_array ;
$entry [ "groupType" ] = "2" ; //GroupType="2" is Distribution / GroupType="1" is Security

Ldap_add ($ds , $base_dn , $entry );

Ldap_close ($ds );
} else {
echo "Unable to connect to LDAP server" ;
}
?>

14 years ago

Another fun thing: ldap_add() doesn"t like arrays with empty members: so
array (
= "name"
= ""
= "value"
will yield a syntax error!

solve this with a simple peice of code:

foreach ($originalobject as $key => $value){
if ($value != ""){
$object[$key] = $value;
}
}

where $originalobject is the uncecked array and $object is the one without empty members.

19 years ago

Ldap_add() will only honour the $entry["attribute"][x]="value" *if there are multiple values for the attribute*. If there is only one attribute value, it *MUST* be entered as $entry["attribute"]="value" or ldap_add() sets the value for the attribute to be "Array" instead of what you put into $entry["attribute"].

Here is a little routine I wrote up to do this automatically. when you"re parsing the input, just use multi_add():
function multi_add ($attribute , $value )
{
global $entry ; // the LDAP entry you"re gonna add

If(isset($entry [ $attribute ]))
if(is_array ($entry [ $attribute ]))
$entry [ $attribute ][ count ($entry [ $attribute ])] = $value ;
else
{
$tmp = $entry [ $attribute ];
unset($entry [ $attribute ]);
$entry [ $attribute ][ 0 ] = $tmp ;
$entry [ $attribute ][ 1 ] = $value ;
}
else
$entry [ $attribute ] = $value ;
}
?>
multi_add() checks to see if there is already a value for the attribute. if not, it adds it as $entry[$attribute]=$value. If there is already a value for the attribute, it converts the attribute to an array and adds the multiple values correctly.

How to use it:
switch($form_data_name )
{
case "phone" : multi_add ("telephoneNumber" , $form_data_value ); break;
case "fax" : multi_add ("facsimileTelephoneNumber" , $form_data_value ); break;
case "email" : multi_add ("mail" , $form_data_value ); break;
...
}
?>
In the system I designed the form has pulldowns with names ctype1, ctype2, ctype3, etc. and the values are "fax, mail, phone...". The actual contact data (phone number, fax, email, etc) is contact1, contact2, contact3, etc. The user pulls down what the contact type is (phone, email) and then enters the data (number, address, etc.)

I use variable variables to fill the entry and skip blanks. Makes for a very clean form entry system. email me if you"re interested in it, as I think I"m outgrowing the size of note allowed here. :-)

6 years ago

I kept getting "Object Class Violation" when I tried adding posixAccount and shadowAccount as an objectclass. It turned out that these object classes had a lot of required fields that I was not adding. You may need to export a working user (if you have phpLDAPadmin) and see exactly what fields they have, then try to copy it exactly in the script. It also doesn"t hurt if you make everything an Array the first time around, you can fix those fields later.

In this section, you"ll learn how to search and retrieve data from the directory server, as well as add, modify, and delete entries.

ldap_search()

resource ldap_search (resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
The ldap_search() function offers a powerful means for searching the directory server pointed to by link_identifier. It will search to a depth of LDAP_SCOPE_SUBTREE, a value that can be set via the previously introduced function ldap_set_option(). By default, this value is set to search to an infinite depth, or through the entire scope of the tree as defined by the base_dn. The search filter, equivalent to a relational database query, is passed in via the filter parameter. Finally, you can specify exactly which attributes should be returned within the search results via the attributes parameter. The remaining four parameters are optional, and therefore in the interests of space, I"ll leave it as an exercise to you to learn more about them. Let"s consider an example:

"; } ldap_unbind($ad); ?> A sampling of the results follow: Gilmore, Jason (Columbus) Shoberg, Jon (Columbus) Streicher, Martin (San Francisco) Wade, Matt (Orlando)

Most of this is likely straightforward, save for the potentially odd way in which attribute values are referenced. All attribute rows are ultimately multi-dimensional arrays, with each attribute value referenced by a combination of row number, attribute name, and attribute array index. So, for example, even attributes such as "sn", the attribute name for the user"s last name, is an indexed array.

ldap_mod_add()

boolean ldap_mod_add(resource link_id, string dn, array entry)
Adding entries to the directory server is accomplished via the ldap_mod_add() function. A new entry is added simply by creating an array consisting of the attribute/value mappings intended to comprise the new row. This process is perhaps best explained with an example:

As is the case with all directory server tasks, be sure that the binding user has proper permissions to add the target data; otherwise, errors will occur.

ldap_mod_replace()

boolean ldap_mod_replace(resource link_id, string dn, array entry)
Modifying entry attributes is accomplished via the ldap_mod_replace() function. It operates exactly like ldap_add(), save for the added step of identifying the entry you"d like to modify. This is done by pointing to a very specific dn. Like ldap_add(), both a valid link identifier and an array consisting of the entries you"d like to update must be provided. An example follows, demonstrating how a user"s telephone number would be modified. In particular, take note of the very specific DN (pointing to my particular entry).

As is the case with all directory server tasks, be sure that the binding user has proper permissions to modify the target data; otherwise, unexpected errors will occur.

ldap_delete()

boolean ldap_delete(resource link_id, string dn)
Rounding out our survey of key PHP LDAP functions is ldap_delete(). This function is used to delete an existing entry. Like ldap_mod_replace(), a very specific DN must be provided to effect the deletion. The following example demonstrates how to remove the "Jason Gilmore" user entry from Active Directory:

As is the case with all directory server tasks, be sure that the binding user has proper permissions to delete the target data; otherwise, unexpected errors will occur.

Searching Active Directory via the Web

I always like to round out a tutorial with an applicable example that readers can immediately adapt to their own needs. In this tutorial, I"ll show you how to create a search interface capable of searching by name, location, or phone number. All you"ll need to do is modify the connection variables and base DN. To begin, let"s create the search interface, which will be saved as "search.html":

Search criteria:

Filter:

Figure 1 offers an example of what this search form would look like in the browser.

Figure 1. The Active Directory Search Form

Next, we"ll need to create the logic that effects the search. This short bit of code is shown here:

0) { for ($i=0; $i<$entries["count"]; $i++) { echo "

Name: ".$entries[$i]["displayname"]."
"; echo "Phone: ".$entries[$i]["telephonenumber"]."
"; echo "Email: ".$entries[$i]["mail"]."

"; } } else { echo "

No results found!

"; } ldap_unbind($ad); ?>

You can either change the action destination specified in the search interface, pointing it to a file consisting of the above script, or you can bundle it into the same file as the search interface, and use isset() and an if conditional to trigger execution in the case that the search submit button is depressed. Of course, you"ll want to add some additional data validation criteria prior to deploying such a script. Figure 2 offers a sampling of the search results.

Figure 2. Search Results

Conclusion

Although PHP has long been my primary language for developing Web applications, I"ve found Perl to be an integral part of my programmer"s toolkit. When working with directory servers, this sentiment is no different. Therefore, the next article is devoted to Perl/LDAP basics. As was the case with this article, all examples are specific to Microsoft"s Active Directory, although you should be able to easily apply them to any directory server implementation. We"ll round out that article with an example demonstrating how to create statically cached Web-based user directories using a Perl script and CRON (or Windows Task Scheduler).

I welcome questions and comments! E-mail me at [email protected] . I"d also like to hear more about your experiences integrating Microsoft and Open Source technologies!

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is an Internet application developer for the Fisher College of Business. He"s the author of the upcoming book, PHP 5 and MySQL: Novice to Pro, due out by Apress in 2004. His work has been featured within many of the computing industry"s leading publications, including Linux Magazine, O"Reillynet, Devshed, Zend.com, and Webreview. Jason is also the author of A Programmer"s Introduction to PHP 4.0 (453pp., Apress). Along with colleague Jon Shoberg, he"s co-author of "Out in the Open," a monthly column published within Linux magazine.

IT Solutions Builder TOP IT RESOURCES TO MOVE YOUR BUSINESS FORWARD