-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActiveDirectoryAuthenticator.cs
310 lines (266 loc) · 11.8 KB
/
ActiveDirectoryAuthenticator.cs
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Linq;
using System.Collections;
using System.DirectoryServices.ActiveDirectory;
namespace AdTest
{
public class UserDetail
{
/// <summary>
/// ID of user if available in end system, or otherwise the username as ID
/// </summary>
public string Id { get; set; }
/// <summary>
/// Username. Typically User Principal Name or similar
/// </summary>
public string Username { get; set; }
/// <summary>
/// Email, which may be different from username
/// </summary>
public string Email { get; set; }
/// <summary>
/// Full name of user
/// </summary>
public string FullName { get; set; }
/// <summary>
/// First name of user
/// </summary>
public string Name { get; set; }
/// <summary>
/// Given name of user
/// </summary>
public string GivenName { get; set; }
/// <summary>
/// Middle name of user
/// </summary>
public string MiddleName { get; set; }
/// <summary>
/// Surname of user
/// </summary>
public string Surname { get; set; }
/// <summary>
/// Description value for the account if relevant
/// </summary>
public string Description { get; set; }
/// <summary>
/// Account name if relevant (e.g. SAM account)
/// </summary>
public string AccountName { get; set; }
/// <summary>
/// Distinguished Name if relevant (e.g. DN on auth systems using a DN concept)
/// </summary>
public string DistinguishedName { get; set; }
/// <summary>
/// Count of bad logon attempts if available
/// </summary>
public int BadLogonCount { get; set; }
/// <summary>
/// Full property list, as string keys and values
/// </summary>
public IDictionary<string, string> Properties { get; set; }
/// <summary>
/// Domain controller details were fetched from if known
/// </summary>
public string DomainController { get; set; }
}
public class User
{
/// <summary>
/// ID of user if available in end system, or otherwise the username as ID
/// </summary>
public string Id { get; set; }
/// <summary>
/// Username. Typically User Principal Name or similar
/// </summary>
public string Username { get; set; }
/// <summary>
/// Email, which may be different from username
/// </summary>
public string Email { get; set; }
/// <summary>
/// Full name of user
/// </summary>
public string FullName { get; set; }
}
/// <summary>
/// Implements Active Directory authentication
/// </summary>
public class ActiveDirectoryAuthenticator
{
private const uint E_USERNAME_OR_PASSWORD_INVALID = 0x8007052E;
public async Task<string> GetDomainController(string username, string password, string domain = null)
{
return await Task.Run(() =>
{
try
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domain, username, password);
var domainInfo = Domain.GetDomain(domainContext);
var controller = domainInfo.FindDomainController();
return controller.Name;
}
catch (Exception)
{
return null;
}
}).ConfigureAwait(false);
}
/// <summary>
/// Authenticate user by username and password
/// </summary>
/// <param name="username">username or user principle name (domain\username or email format)</param>
/// <param name="password">password</param>
/// <param name="domain">optional domain</param>
/// <param name="container">optional container string</param>
/// <param name="withProperties">if true, adds additional properties</param>
/// <returns>Authenticated user details or null if not authenticated</returns>
/// <exception cref="UnableToAuthenticateException">Thrown if there is an error authenticating</exception>
public async Task<UserDetail> Authenticate(string username, string password, string domain = null, string container = null, bool withProperties = false, ContextOptions? options = null)
{
return await Task.Run(() =>
{
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, container))
{
// validate the credentials. Uses either method to allow specifying options and default without.
bool isValid;
if (options.HasValue)
isValid = context.ValidateCredentials(username, password, options.Value);
else
isValid = context.ValidateCredentials(username, password);
if (isValid == false)
return null;
// get user and dump details
UserPrincipal foundUser = FindUser(context, username);
if (foundUser != null)
{
string userPrincipalName = foundUser.UserPrincipalName.Trim();
if (string.IsNullOrEmpty(userPrincipalName))
{
throw new UnableToAuthenticateException("User has no User Principal Name");
}
var authenticatedUser = new UserDetail
{
// Use Guid for Id if available, otherwise email address
Id = foundUser.Guid.HasValue ? foundUser.Guid.ToString() : userPrincipalName.ToLower(),
Username = userPrincipalName,
Email = string.IsNullOrEmpty(foundUser.EmailAddress) == false ? foundUser.EmailAddress : userPrincipalName,
FullName = foundUser.DisplayName,
Name = foundUser.Name,
GivenName = foundUser.GivenName,
MiddleName = foundUser.MiddleName,
Surname = foundUser.Surname,
Description = foundUser.Description,
AccountName = foundUser.SamAccountName,
DistinguishedName = foundUser.DistinguishedName,
BadLogonCount = foundUser.BadLogonCount,
DomainController = context.ConnectedServer
};
// Populate underlying properties
if (withProperties && foundUser.GetUnderlyingObject() is DirectoryEntry de && de.Properties.Count > 0)
{
authenticatedUser.Properties = new Dictionary<string, string>();
IDictionaryEnumerator ide = de.Properties.GetEnumerator();
ide.Reset();
while (ide.MoveNext())
{
PropertyValueCollection property = ide.Entry.Value as PropertyValueCollection;
authenticatedUser.Properties.Add(property.PropertyName.ToString(), property.Value.ToString());
}
}
return authenticatedUser;
}
}
}
catch (COMException ex)
{
// Sometimes ValidateCredentials doesn't just return false for invalid credentials, it throws a COMException!
if ((uint)ex.ErrorCode == E_USERNAME_OR_PASSWORD_INVALID)
{
return null;
}
// Something else
throw new UnableToAuthenticateException(ex.Message, ex);
}
catch (PrincipalServerDownException ex)
{
throw new UnableToAuthenticateException(ex.Message, ex);
}
catch (UnableToAuthenticateException)
{
throw;
}
catch (Exception ex)
{
throw new UnableToAuthenticateException(ex.Message, ex);
}
return null;
}).ConfigureAwait(false);
}
public Task<List<User>> GetUsers(string domain = null, string container = null)
{
return Task.Run(() =>
{
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, container))
{
var upList = GetUsers(context);
IEnumerable<User> users = from u in upList
let userPrincipalName = u.UserPrincipalName?.Trim().ToLower()
orderby u.DisplayName
select new User
{
Id = u.Guid.HasValue ? u.Guid.ToString() : userPrincipalName.ToLower(),
Username = userPrincipalName,
FullName = u.DisplayName,
Email = string.IsNullOrEmpty(u.EmailAddress) == false ? u.EmailAddress : userPrincipalName
};
return users.ToList();
}
}
catch (Exception)
{
}
return null;
});
}
private static UserPrincipal FindUser(PrincipalContext context, string username)
{
// Find by UPN
var up = new UserPrincipal(context) { UserPrincipalName = username };
var search = new PrincipalSearcher(up);
if (search.FindOne() is UserPrincipal foundUser)
return foundUser;
// Find by SAM
up = new UserPrincipal(context) { SamAccountName = username };
search = new PrincipalSearcher(up);
foundUser = search.FindOne() as UserPrincipal;
if (foundUser != null)
return foundUser;
return null;
}
private static IEnumerable<UserPrincipal> GetUsers(PrincipalContext context)
{
var up = new UserPrincipal(context);
var search = new PrincipalSearcher(up);
var users = from p in search.FindAll()
let u = p as UserPrincipal
where u != null && u.UserPrincipalName != null
select u;
if (users != null && users.Any())
return users;
return null;
}
}
public class UnableToAuthenticateException : Exception
{
public UnableToAuthenticateException(string message, Exception innerException = null) : base(message, innerException) { }
}
}