Форум программистов, компьютерный форум, киберфорум
anomal6
Войти
Регистрация
Восстановить пароль
Карта форума Блоги Сообщество Поиск Заказать работу  
Рейтинг: 5.00. Голосов: 1.

Active Directory Логин, получение данных c#

Запись от anomal6 размещена 27.03.2020 в 13:11

Всем привет.
Сегодня хочу поделиться знаниями с Active Directory, а именно :
1. Попробуем залогинится.
2. Получим данные того или иного пользователя.


Первоначально подключим пространство имён
C#
1
2
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
Для проверки логина и пароля будем использовать возвращаемую булевую
На форму бросим два TextBox'а и одну кнопку

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 public bool ValidateUser(string userName, string password)
        {
            bool validation;
            try
            {
                LdapConnection ldc = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
                NetworkCredential nc = new NetworkCredential(userName, password, "Your Domain");
                ldc.Credential = nc;
                ldc.AuthType = AuthType.Negotiate;
                ldc.Bind(nc); // тут юзер прошел аутентификацию, так как учетные данные были использованы для входа в систему.
                validation = true;
            }
            catch (LdapException ldap_ex)
            {
                validation = false;
                MessageBox.Show(ldap_ex.Message + "\r\n" + ldap_ex.ServerErrorMessage, ldap_ex.HelpLink, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return validation;
        }
А проверять будем так
C#
1
2
3
4
5
6
7
private void Button1_Click(object sender, EventArgs e)
        {
            if(ValidateUser(textBox_Login.Text, textBox_Passwd.Text))
            {
                MessageBox.Show("Логин и пароль верны!");
            }
        }
И всё!
Но залогиниться это одно, но вот теперь получим данные попробуем

Закинем на форму ListView один ComboBox и ещё один TextBox
Добавим так же контекстное меню и будем вызывать.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void GetDomaiUsers(RichTextBox rtb)
        {
            var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x-y.z", "OU=Users,DC=x-y,DC=z"));
            var searcher = new DirectorySearcher(dirEntry)
            {
                Filter = "(&(&(objectCategory=person)(objectClass=user)))"
                //Тут укажем фильтр поиска
            };
 
            foreach (SearchResult result in searcher.FindAll())
            {         
                var entry = result.GetDirectoryEntry();
                de = result.GetDirectoryEntry();
                string ADName, Test, I, F, EMail, MobileNumber, NumberFull, guid;
                try
                {                 
                    comboBox1.Items.Add(entry.Properties["cn"].Value);
                    ListViewItem item = new ListViewItem(new string[] {
                    ADName = entry.Properties["cn"].Value != null ? entry.Properties["cn"].Value.ToString() : "NoN",
                    F = entry.Properties["sAMAccountName"].Value != null ? entry.Properties["sAMAccountName"].Value.ToString() : "NoN",
                    EMail = entry.Properties["mail"].Value != null ? entry.Properties["mail"].Value.ToString() : "NoN",
                    MobileNumber = entry.Properties["mobile"].Value != null ? entry.Properties["mobile"].Value.ToString() : "NoN",
                    NumberFull = entry.Properties["telephoneNumber"].Value != null ? entry.Properties["telephoneNumber"].Value.ToString() : "NoN",
                     Test = entry.Properties["adminDescription"].Value != null ? entry.Properties["adminDescription"].Value.ToString() : "NoN",
                     guid = entry.Guid.ToString(),
                });
                    listView1.Items.Add(item);
                }
                catch { }
 
            }
        }
Фильтры поиска можно найти на MSDN
В ListView Добавили, теперь будем у каждого полученного пользователя узнавать все данные по атрибутам
Все атрибуты можно найти здесь
Их не мало, и во всех не смог разобраться.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void ПоАтрибутуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            string show;
            var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x-y.z", "OU=Users,DC=x-y,DC=z"));
            var searcher = new DirectorySearcher(dirEntry)
            {
                Filter = $"(&(&(objectCategory=person)(objectClass=user)(cn={listView1.SelectedItems[0].Text})))"
            };
            foreach (SearchResult result in searcher.FindAll())
            {
                var entry = result.GetDirectoryEntry();
                try
                {
                    show = entry.Properties[attribute.Text].Value != null ? entry.Properties[attribute.Text].Value.ToString() : "NoN";                  
                    MessageBox.Show(show, listView1.SelectedItems[0].Text);   
                }
                catch (Exception ex) { MessageBox.Show(ex.ToString());
            }
        }
Ну и напоследок узнаем всё что возможно о Юзере

Для начала добавим все атрибуты в массив

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
 string[] query = { "accountExpires",
"adminDescription",
"adminDisplayName",
"ADsPath",
"altRecipient",
"altRecipientBL",
"authOrig",
"authOrigBL",
"autoReplyMessage",
"badPasswordTime",
"badPwdCount",
"c (Country)",
"canonicalName",
"Class",
"co (Country)",
"comment",
"company",
"countryCode",
"createTimeStamp",
"deletedItemFlags",
"delivContLength",
"deliverAndRedirect",
"department",
"departmentNumber",
"description",
"directReports",
"displayName",
"displayNamePrintable",
"distinguishedName",
"division",
"dLMemRejectPerms",
"dLMemRejectPermsBL",
"dLMemSubmitPerms",
"dLMemSubmitPermsBL",
"employeeID",
"employeeNumber",
"employeeType",
"extensionData",
"extensionAttribute1 - 15",
"facsimileTelephoneNumber",
"garbageCollPeriod",
"givenName",
"homeDirectory",
"homeDrive",
"homeMDB",
"homeMTA",
"homePhone",
"info",
"initials",
"ipPhone",
"isDeleted",
"isRecycled",
"l (Location)",
"lastKnownParent",
"lastLogoff",
"lastLogon",
"lastLogonTimestamp",
"legacyExchangeDN",
"lockoutTime",
"logonCount",
"logonHours",
"mail",
"mailNickname",
"manager",
"mDBOverHardQuotaLimit",
"mDBOverQuotaLimit",
"mDBStorageQuota",
"mDBUseDefaults",
"memberOf",
"mobile",
"modifyTimeStamp",
"msCOM-UserPartitionSetLink",
"Control-Computed",
"msDS-UserPassword",
"ExpiryTimeComputed",
"msExchHideFromAddressLists",
"msExchHomeServerName",
"msExchMailboxSecurityDescriptor",
"msExchMasterAccountSID",
"msExchOmaAdminWirelessEnable",
"msExchPoliciesExcluded",
"msExchRecipLimit",
"msExchRequireAuthToSendTo",
"msExchUserAccountControl",
"msNPAllowDialin",
"msNPCallingStationID",
"msNPSavedCallingStationID",
"msRADIUSCallbackNumber",
"msRADIUSFramedIPAddress",
"msRADIUSFramedRoute",
"msRADIUSServiceType",
"msRASSavedCallbackNumber",
"msRASSavedFramedIPAddress",
"msRASSavedFramedRoute",
"msSFU30GidNumber",
"msSFU30HomeDirectory",
"msSFU30LoginShell",
"msSFU30Name",
"msSFU30NisDomain",
"msSFU30Password",
"msSFU30UidNumber",
"name",
"Name (ADSI Property)",
"nTSecurityDescriptor",
"objectCategory",
"objectClass",
"objectGUID",
"objectSid",
"otherFacsimileTelephoneNumber",
"otherHomePhone",
"otherIpPhone",
"otherMobile",
"otherPager",
"otherTelephone",
"pager",
"Parent",
"physicalDeliveryOfficeName",
"postalCode",
"postOfficeBox",
"primaryGroupID",
"profilePath",
"protocolSettings",
"proxyAddresses",
"publicDelegates",
"publicDelegatesBL",
"pwdLastSet",
"sAMAccountName",
"scriptPath",
"seeAlso",
"securityProtocol",
"sIDHistory",
"sn (Surname)",
"st (State)",
"streetAddress",
"submissionContLength",
"telephoneNumber",
"textEncodedORAddress",
"title",
"unauthOrig",
"unauthOrigBL",
"url",
"userAccountControl",
"userCertificate",
"userParameters",
"userPrincipalName",
"userWorkstations",
"uSNChanged",
"uSNCreated",
"whenChanged", };
Некоторыe атрибуты считываются не быстро поэтому сделаем метод асинхронный
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async private void ИнформацияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x-y.z", "OU=Users,DC=x-y,DC=z"));
            var searcher = new DirectorySearcher(dirEntry)
            {
                Filter = $"(&(&(objectCategory=person)(objectClass=user)(cn={listView1.SelectedItems[0].Text})))"
            };
          
            foreach (SearchResult result in searcher.FindAll())
            {
                var entry = result.GetDirectoryEntry();
            try
                {               
                    for (int i = 0; i < query.Length; i++)
                    {                     
                        if(entry.Properties[query[i]].Value != null && entry.Properties[query[i]].Value == entry.Properties[query[i]].Value.ToString())
                        {
                            richTextBox1.Text += query[i] + " - " + entry.Properties[query[i]].Value.ToString() + Environment.NewLine;
                            await Task.Delay(50);
                        }
                    }               
                }
                catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            }
        }
Нажмите на изображение для увеличения
Название: 1.png
Просмотров: 1231
Размер:	133.4 Кб
ID:	6051
Нажмите на изображение для увеличения
Название: 2.png
Просмотров: 1163
Размер:	32.9 Кб
ID:	6050
Нажмите на изображение для увеличения
Название: 3.png
Просмотров: 1215
Размер:	109.8 Кб
ID:	6049

P.S. не забывайте о том, что при запуске программы, ваш компьютер должен быть в доменной сети, иначе получите ошибку.
Или запустите программу от имени того пользователя кто состоит в домене
Вложения
Тип файла: 7z AD LDAP.7z (164.8 Кб, 1139 просмотров)
Размещено в Без категории
Показов 3271 Комментарии 0
Всего комментариев 0
Комментарии
 
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru