public ImpersonatorUser Finduser(string domainAndUsername) { ImpersonatorUser user = null; //try //{ user = new ImpersonatorUser(); using (HostingEnvironment.Impersonate()) { DirectoryEntry entry = new DirectoryEntry(_path); //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + domainAndUsername + "))"; //search.PropertiesToLoad.Add("cn"); SearchResult results = search.FindOne(); if (results != null) { user.GUID = results.GetDirectoryEntry().Guid; //row["SID"] = GetProperty(results, "sAMAccountName"); user.Username = GetProperty(results, "sAMAccountName"); user.DisplayName = GetProperty(results, "cn"); if (results.Path.IndexOf("OU=") > 0) { string temp = results.Path.Substring(results.Path.IndexOf("OU=") + 3); user.OU = temp.Substring(0, temp.IndexOf(","));; } user.Department = GetProperty(results, "department"); user.Title = GetProperty(results, "title"); user.Email = GetProperty(results, "mail"); user.Phone = GetProperty(results, "mobile"); user.Address = GetProperty(results, "homePostalAddress"); user.Pager = GetProperty(results, "pager"); user.Role = GetGroups(results.GetDirectoryEntry().Path, GetProperty(results, "cn")); } else { return(null); } } //} //catch (Exception ex) //{ // throw new Exception("Error authenticating user. Message {" + ex.Message + "} - Inner exception {" + ex.InnerException + "}"); //} return(user); }
public ImpersonatorUser FindUser(string username) { ImpersonatorUser user = new ImpersonatorUser(); try { DirectoryEntry _entry = new DirectoryEntry("WinNT://" + _servername + ",computer"); _entry.Children.SchemaFilter.Add("User"); if (username.Contains("\\")) { username = username.Substring(username.LastIndexOf('\\') + 1); } foreach (DirectoryEntry _child in _entry.Children) { if (_child.Name.Equals(username, StringComparison.OrdinalIgnoreCase)) { SecurityIdentifier sid = new SecurityIdentifier((byte[])_child.Properties["objectSID"].Value, 0); user.GUID = _child.Guid; user.SID = sid.ToString(); user.Username = _child.Name; user.DisplayName = _child.Properties["fullname"].Value.ToString(); object obGroups = _child.Invoke("Groups"); foreach (object ob in (IEnumerable)obGroups) { // emumerate through groups DirectoryEntry obGpEntry = new DirectoryEntry(ob); user.Role += string.Format("{0}|", obGpEntry.Properties["Name"].Value); } if (user.Role != string.Empty) { user.Role = user.Role.Remove(user.Role.LastIndexOf('|')); } break; } } } catch (Exception ex) { throw new Exception("Error authenticating user. Message {" + ex.Message + "} - Inner exception {" + ex.InnerException + "}"); } return(user); }